1745. K-Way Rope Joiner
A recycling plant has piles of scrap, with piles[i] being the weight of pile i. A crusher can merge between 2 and k piles in one run, producing a single pile whose weight is the sum, and the run costs exactly that merged weight. The plant keeps merging until only one pile remains.
Return the minimum possible total cost as a long; if there is only one pile the answer is 0. Merging fewer than k piles is the same as merging k piles where some have weight zero, so the intended solution pads the list with zero-weight piles until (n - 1) % (k - 1) == 0 and then repeatedly merges the k lightest piles taken from a min-heap, in O((n + k) log n) time.
Example 1
- Input:
- piles = [4,3,2,1], k = 2
- Output:
- 19
- Explanation:
Merge 1+2 for 3, then 3+3 for 6, then 4+6 for 10, costing 3 + 6 + 10 = 19.
Example 2
- Input:
- piles = [5,2,7], k = 3
- Output:
- 14
- Explanation:
All three piles fit in one run of the crusher, which costs 5 + 2 + 7 = 14.
Example 3
- Input:
- piles = [1,2,3,4], k = 3
- Output:
- 13
- Explanation:
Merge the two lightest piles first (cost 3), then merge 3, 3 and 4 together (cost 10), for a total of 13.
Constraints
1 ≤ n ≤ 105 (n = piles.length)
2 ≤ k ≤ 105
1 ≤ piles[i] ≤ 104
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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O((n + k) log n)
- Space
- O(n + k)