LC1043. Partition Array for Maximum Sum

Given an integer array A, you partition the array into (contiguous) subarrays of length at most K.  After partitioning, each subarray has their values changed to become the maximum value of that subarray.

Return the largest sum of the given array after partitioning.

分析:明显的动态规划, dp[i] 表示从 A[0]~A[i] 能得到的最大值,显然,当前状态和前K个状态相关,取最大值即可

time:$O(NK)$

space: $O(N)$

int maxSumAfterPartitioning(vector<int>& A, int K) {
        int N = A.size();
        vector<int> dp(N);
        for (int i = 0; i < N; ++i) {
            int curMax = 0;
            for (int k = 1; k <= K && i - k + 1 >= 0; ++k) {
                curMax = max(curMax, A[i - k + 1]);
                dp[i] = max(dp[i], (i >= k ? dp[i - k] : 0) + curMax * k);
            }
        }
        return dp[N - 1];
    }

 

上一篇:手撕腾讯面试题-乘积最大子数组


下一篇:152. 乘积最大子序列