394. Partition Array for Maximum Sum
You are given an integer array arr with length n, and an integer k.
You may partition arr into one or more contiguous sub-arrays, where each sub-array has length in the range 1 … k (inclusive).
After you pick a partition, replace every element in each sub-array with the maximum value found in that sub-array. The array is modified in-place for the purpose of computing the total.
Return the largest possible sum of the entire array after performing exactly one such partition-and-replace operation.
The test cases are guaranteed to have an answer that fits in a 32-bit signed integer.
Example 1:
Input: arr = [1,15,7,9,2,5,10], k = 3
Output: 84
Explanation:
Choose blocks
- [1,15,7] → max = 15,
- [9] → max = 9,
- [2,5,10] → max = 10.
- The array becomes [15,15,15,9,10,10,10]; sum = 84.
Example 2:
Input: arr = [2,2,2,2], k = 2
Output: 8
Explanation:
- Partition as [2,2] and [2,2]; each sub-array’s max is 2.
- The array stays [2,2,2,2] and the sum is 8.
Now Your Turn!
Pick the correct output for the given inputInput: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
Output: 83
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ≤ arr.length ≤ 500
- 0 ≤ arr[i] ≤ 10⁹
- 1 ≤ k ≤ arr.length