You get a list of non-negative numbers, nums, and a number k. Cut the list into exactly k pieces. Each piece is a run of neighbouring numbers and holds at least one number; together the pieces use every number once, in order.
Each piece has a sum. Choose the cuts so that the biggest of those sums is as small as possible, and return that biggest sum.
Example 1
Input: nums = [6, 3, 8, 1, 4], k = 2 Output: 13 Why: [6, 3] and [8, 1, 4] have sums 9 and 13; every other cut is worse
2 more examples and the constraints
Example 2
Input: nums = [1, 4, 2, 6, 3], k = 3 Output: 7 Why: [1, 4, 2], [6], [3] have sums 7, 6 and 3
Example 3
Input: nums = [9, 0, 1], k = 1 Output: 10 Why: one piece must hold everything
Constraints
- 1 ≤ length of nums ≤ 1,000
- 0 ≤ nums[i] ≤ 1,000,000
- 1 ≤ k ≤ 50, and k is at most the length of nums
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Dynamic programmingO(k·n²)
- Binary search on the answerO(n log S)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 1,000, k = 50 | Verdict |
|---|---|---|---|
| Dynamic programming | O(k·n²) | Correct; heavy at the limits | |
| Binary search on the answer | O(n log S) | Best; a few dozen greedy passes |
n = length of nums, k = number of pieces, S = sum of nums.
Edge cases to test
- k equals the length. Every number is its own piece, so the answer is the largest number: [3, 1, 4, 1, 5] with k = 5 gives 5.
- k is 1. One piece holds everything, so the answer is the total sum.
- Zeros. [0, 0, 0] with k = 2 gives 0; the search starts and ends at 0.
- Big sums. 1,000 numbers of 1,000,000 sum to a billion, close to the 32-bit limit; add in a 64-bit type.
Common mistakes
- Starting
loat 0 or 1 instead ofmax(nums), which lets the greedy check pass with a piece that cannot hold a single number. - Requiring the greedy count to equal
kexactly instead of at mostk. - Writing
lo = midwhenmidfails, so the search never ends.
How to talk through it
- 1Clarify. Pieces must be contiguous and non-empty? Can numbers be zero? Do I return the sum or the cuts?
- 2Give the DP. Define the best split of a prefix into j pieces and try every last cut: O(k·n²).
- 3Flip the question. Checking a fixed limit is a greedy pass, and the answer is monotone in the limit, so binary search it.
- 4Code the check, then the search. Count pieces with a running sum, then search between the largest number and the total.
- 5Test out loud. Run k = 1, k = n and a list with zeros before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?