824. Merge the Piles
A dock has stones, a row of cargo piles where stones[i] is the weight of pile i. A crane can combine exactly k neighbouring piles into one pile in a single operation, and the operation costs the total weight of those k piles; the new pile takes their place in the row.
Return the minimum total cost of operations that reduce the whole row to a single pile, or -1 if it cannot be done (for instance when the number of piles cannot be reduced to one by repeatedly removing k - 1 piles). A row that already holds one pile costs 0.
Aim for time O(n^3 / k) and space O(n^2), where n is stones.length.
Example 1
- Input:
- stones = [4,7,2,9], k = 2
- Output:
- 44
- Explanation:
Merge 4+7 (cost 11), then 2+9 (cost 11), then the two results (cost 22), for a total of 44.
Example 2
- Input:
- stones = [3,6,1,8,5], k = 3
- Output:
- 33
- Explanation:
Merge the first three piles (cost 10) and then 10, 8 and 5 (cost 23), for a total of 33.
Constraints
1 ≤ stones.length ≤ 201
1 ≤ stones[i] ≤ 100
2 ≤ k ≤ 30
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n^3 / k)
- Space
- O(n^2)