2024-02-03 Daily Challenge
Today I have done leetcode's February LeetCoding Challenge with cpp
.
February LeetCoding Challenge 3
Description
Partition Array for Maximum Sum
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.
Example 1:
Input: arr = [1,15,7,9,2,5,10], k = 3 Output: 84 Explanation: arr becomes [15,15,15,9,10,10,10]
Example 2:
Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 Output: 83
Example 3:
Input: arr = [1], k = 1 Output: 1
Constraints:
1 <= arr.length <= 500
0 <= arr[i] <= 109
1 <= k <= arr.length
Solution
class Solution {
public:
int maxSumAfterPartitioning(vector<int>& arr, int k) {
vector<int> dp(arr.size());
dp[0] = arr[0];
for(int i = 1; i < arr.size(); ++i) {
int mmax = INT_MIN;
for(int j = i; j >= max(0, i - k + 1); --j) {
mmax = max(mmax, arr[j]);
dp[i] = max(dp[i], (j ? dp[j - 1] : 0) + (i - j + 1) * mmax);
}
}
return dp.back();
}
};
// Accepted
// 52/52 cases passed (3 ms)
// Your runtime beats 99.46 % of cpp submissions
// Your memory usage beats 23.07 % of cpp submissions (10.9 MB)