Partition Array for Maximum Sum
Implement maxSumAfterPartitioning
Cut an array into contiguous groups, each no longer than `k`, then replace every element of a group with that group's own largest value. Choose the grouping that makes the total, after every replacement, as large as possible.
Once a group's length is fixed, its contribution is fixed too — the group's maximum, counted once per element in it — so the only real decision at each position is how long the next group should run, from 1 up to k. Reaching some position i for the first time as the start of a fresh group means an earlier position was already settled optimally, and the stretch between them is exactly one new group. So the best total ending at i is the best total ending at some valid earlier cut, plus that new group's contribution — and trying every legal group length at every position, building left to right, means every earlier answer needed is already on hand.
Example 1:
Input: arr = [1,15,7,9,2,5,10], k = 3
Output: 84
Example 2:
Input: arr = [1,2,3], k = 1
Output: 6
Example 3:
Input: arr = [1], k = 15
Output: 1
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ arr.length ≤ 10 - ●
1 ≤ k ≤ arr.length - ●
1 ≤ arr[i] ≤ 1000
arr =
[1, 15, 7, 9, 2, 5, 10]
k =
3