Partition Array for Maximum Sum

Given an integer array arr, split it into contiguous subarrays of length at most k. After partitioning, every value in a subarray becomes the maximum of that subarray. Return the largest possible sum of the array after partitioning.

30:00

Partition Array for Maximum Sum
medium
Free written solution
Topics
Companies

Given an integer array arr, split it into contiguous subarrays of length at most k. After partitioning, every value in a subarray becomes the maximum of that subarray. Return the largest possible sum of the array after partitioning.

Example 1:
Input: {"arr":[1,15,7,9,2,5,10],"k":3}
Output: 84
Constraints:
  • 1≤arr.length≤5001 \leq \text{arr.length} \leq 500

  • 0≤arr[i]≤1090 \leq \text{arr}[i] \leq 10^9

  • 1≤k≤arr.length1 \leq k \leq \text{arr.length}

  • The answer fits in a 32-bit integer.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[1,15,7,9,2,5,10],"k":3}

dp[i] = best sum for the first i numbers. dp[0] = 0. For each i, try every length (up to k = 3) for the LAST block; that block is flattened to its maximum.

k = 3 (blocks of length 1..3)

1

0

15

1

7

2

9

3

2

4

5

5

10

6

dp[j] = best sum of the first j elements

dp[0]

0

dp[1]

?

dp[2]

?

dp[3]

?

dp[4]

?

dp[5]

?

dp[6]

?

dp[7]

?

Variables
VariableValue
n7
k3
DepthFunction Call
Stack empty
0/26