You are given an array nums of positive numbers and a number k. Cut the array into at most k pieces. Every piece must be non-empty and made of neighbouring numbers, and every number must be in some piece.
The score of a cut is the sum of the averages of its pieces. Return the highest score you can reach. Answers within 0.000001 of the true value count as correct.
Example 1
Input: nums = [6, 2, 4, 8], k = 2 Output: 12.0 Why: [6, 2, 4] and [8] score 4 + 8 = 12
2 more examples and the constraints
Example 2
Input: nums = [4, 10, 2, 2, 8], k = 3 Output: 18.0 Why: [4], [10] and [2, 2, 8] score 4 + 10 + 4 = 18
Example 3
Input: nums = [3, 3, 6], k = 1 Output: 4.0 Why: one piece, so the score is the plain average
Constraints
- 1 ≤ length of nums ≤ 100
- 1 ≤ nums[i] ≤ 10,000
- 1 ≤ k ≤ length of nums
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with memoO(k·n²)
- Bottom-up DP, one rowO(k·n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 numbers, k = 100 | Verdict |
|---|---|---|---|
| Recursion with memo | O(k·n²) | Passes; recursion and a cache | |
| Bottom-up DP, one row | O(k·n²) | Best; same work, O(n) memory |
n = length of nums, k = most pieces allowed.
Edge cases to test
- k = 1. Only one piece: return the average of the whole array.
- k equals the length. Every number on its own: the score is the plain sum.
- One number. [7] with k = 1 gives 7.
- All numbers equal. Every piece has the same average, so more pieces add more.
Common mistakes
- Using integer division for an average and losing the fraction.
- Updating best[i] right to left in the one-row version, so it reads this round’s values.
- Allowing a piece to be empty, which divides by zero.
How to talk through it
- 1Clarify. Must every number be used? Are the numbers positive? Is “at most k” the same as exactly k here?
- 2Set up the recursion. Pick the end of the first piece; the rest is the same problem with k − 1.
- 3Add the memo. Only n·k states exist; prefix sums make each average O(1).
- 4Go bottom-up. Keep one row and fill it k − 1 times, left to right.
- 5Test out loud. Run k = 1 and k = n, where the answers are the average and the sum.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?