Partition Array for Maximum Sum — LeetCode 1043 Python Solution
- Problem
- #1043
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- arr = [1,15,7,9,2,5,10], k = 3
- Output
- 84
- Explanation
- arr becomes [15,15,15,9,10,10,10]
Python solution
class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
f = [0] * (n + 1)
for i in range(1, n + 1):
mx = 0
for j in range(i, max(0, i - k), -1):
mx = max(mx, arr[j - 1])
f[i] = max(f[i], f[j - 1] + mx * (i - j + 1))
return f[n]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times k) |
| Space | O(n), where n is the length of the array arr auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1043. Partition Array for Maximum Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1043. Partition Array for Maximum Sum?
- LeetCode 1043. Partition Array for Maximum Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1043. Partition Array for Maximum Sum?
- The Python solution on this page runs in O(n \times k).
- What is the space complexity of LeetCode 1043. Partition Array for Maximum Sum?
- The Python solution on this page uses O(n), where n is the length of the array arr auxiliary space.
- What topics does LeetCode 1043. Partition Array for Maximum Sum cover?
- LeetCode 1043. Partition Array for Maximum Sum is tagged Array and Dynamic Programming on LeetCode.