Partition Array for Maximum Sum — LeetCode 1043 Python Solution

MediumArrayDynamic Programming
Problem
#1043
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n \times k)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview