# 1043. Partition Array for Maximum Sum | LeetCode Solution

## 1043. Partition Array for Maximum Sum | LeetCode Solution

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 = , k = 1
Output: 1
```

Constraints:

• `1 <= arr.length <= 500`
• `0 <= arr[i] <= 109`
• `1 <= k <= arr.length`

#include<bits/stdc++.h>
class Solution {
public:

int helper(int idx,vector<int>&v,int k,vector<int>&dp){
if(idx==v.size())return 0;
if(dp[idx]!=-1)return dp[idx];
int len=0;
int maxx=INT_MIN;
int ans=INT_MIN;
int n=v.size();
int last=min(idx+k,n);
for(int i=idx; i<last; i++){
len++;
maxx=max(maxx,v[i]);
int sum=len*maxx+helper(i+1,v,k,dp);
ans=max(ans,sum);
}
return dp[idx]=ans;

}

int maxSumAfterPartitioning(vector<int>& arr, int k) {
vector<int>dp(arr.size()+1,-1);
return helper(0,arr,k,dp);
}
};