Given an integer array arr, 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. Test cases are generated so that the answer fits in a 32-bit integer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { int dp[505]; inthelper(vector<int>& A, int k, int p){ if(p == A.size()) return0; if(dp[p] != -1) return dp[p]; int n = A.size(); for(int i = p, ma = 0; i < min(n, p + k); i++) { ma = max(ma, A[i]); dp[p] = max(dp[p], ma * (i - p + 1) + helper(A, k, i + 1)); } return dp[p]; } public: intmaxSumAfterPartitioning(vector<int>& A, int k){ memset(dp, -1, sizeof dp); returnhelper(A,k,0); } };