Scribbling

[C++] 2d DP table with vector 본문

Computer Science/C++

[C++] 2d DP table with vector

focalpoint 2023. 9. 19. 04:14

1937. Maximum Number of Points with Cost

https://leetcode.com/problems/maximum-number-of-points-with-cost/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

class Solution {
public:
    long long maxPoints(vector<vector<int>>& points) {
        int m = points.size();
        int n = points[0].size();
        vector<vector<long long>> dp(m, vector<long long>(n, 0));
        for (int i = 0; i < n; i++) {
            dp[0][i] = points[0][i];
        }
        for (int i = 1; i < m; i++) {
            vector<long long> lefts(n, 0);
            vector<long long> rights(n, 0);
            lefts[0] = dp[i - 1][0];
            for (int j = 1; j < n; j++) {
                lefts[j] = max(lefts[j - 1] - 1, dp[i - 1][j]);
            }
            rights[n - 1] = dp[i - 1][n - 1];
            for (int j = n - 2; j >= 0; j--) {
                rights[j] = max(rights[j + 1] - 1, dp[i - 1][j]);
            }
            for (int j = 0; j < n; j++) {
                dp[i][j] = points[i][j] + max(lefts[j], rights[j]);
            }
        }
        return *max_element(dp[m - 1].begin(), dp[m-1].end());
    }
};