Combine Cards Into a Limited Number of Piles at Minimum Cost
Implement minCombineCost
You have several piles of cards. Combining two piles costs the total number of cards in them and produces one pile of that size. You don't have to combine everything: you only need to end up with at most a given number of piles. Find the minimum total cost to get there.
Combining the two smallest piles each time is cheapest, since a combined pile is charged again whenever it is combined later. The only change from "merge everything" is when to stop — as soon as the pile count reaches the target. A min-heap gives the two smallest piles in O(log n) instead of two full scans.
Example 1:
Input: cards = [4,9,2,6,3], piles = 3
Output: 14
Example 2:
Input: cards = [4,9,2,6,3], piles = 1
Output: 53
Example 3:
Input: cards = [8,8], piles = 2
Output: 0
+ 9 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ cards.length ≤ 50, 1 ≤ piles ≤ 50 - ●
1 ≤ cards[i] ≤ 1000 - ●
Combining two piles of sizes a and b costs a + b and produces one pile of size a + b - ●
Combine piles until at most "piles" piles remain; return the minimum total cost (0 if there are already at most "piles" piles)
cards =
piles =