study
LeetCode#1937
Date: 2024-08-17 20:52
Update: 2024-08-26 14:25


LeetCode #1937. Maximum Number of Points with Cost

Level: Medium

You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.

To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.

However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.

Return the maximum number of points you can achieve.

My Solution:

class Solution {
public:
    long long maxPoints(vector<vector<int>>& points) {
        int m = points.size();
        int n = points[0].size();
        vector<int> v;
        long long score = 0;
        int cx, cy;
        for(int i = 0; i < m; i++){
            int large = INT_MIN;
            //Store index of max
            int index = 0;
            for(int j = 0; j < n; j++){
                //Pick max from a row    
                if(points[i][j] > large){
                    large = points[i][j];
                    index = j;
                }
            }
            v.push_back(index);
            score += large;
        }

        for(int i = 0; i < v.size()-1; i++){
            score -= abs(v[i]-v[i+1]);
        }

        return score;
    }
};