1043. Partition Array for Maximum Sum
Array, DP, AMateList ·Problem Statement
link: LeetCode.cn LeetCode 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:
Input: arr = [1,15,7,9,2,5,10], k = 3
Output: 84
Input: ` arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
**Output:**
83`
Input: arr = [1], k = 1
Output: 1
Constraints: 1 <= arr.length <= 500 0 <= arr[i] <= 109 1 <= k <= arr.length
Solution Approach
The solution uses dynamic programming to iteratively partition the array and calculate the maximum sum by updating each subarray with its maximum value, ensuring the sum is maximized for each possible partition up to length k.
Algorithm
- State Definition: Define d[i] as the maximum sum obtainable by partitioning the first i elements of the array, allowing the last partition to be of length up to k.
- Transition Formula: Update d[i] by iterating backward from the current index i to a maximum of i-k, calculating the maximum value within this subarray and adding it to d[j] (the maximum sum up to j). The transition is d[i] = max(d[i], d[j] + maxValue * (i - j)).
- Initialization and Final Result: Initialize d[0] = 0 (base case) and iterate through the array to fill the DP table. The final answer is stored in d[n], where n is the length of the array.
Implement
class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
d = [0] * (n + 1)
for i in range(1, n + 1):
maxValue = arr[i - 1]
for j in range(i - 1, max(-1, i - k - 1), -1):
d[i] = max(d[i], d[j] + maxValue * (i - j))
if j > 0:
maxValue = max(maxValue, arr[j - 1])
return d[n]