Minimum Cost to Merge Stones
Implement mergeStones
A row of stone piles is given, along with a group size `k`. Every move fuses exactly `k` piles standing next to each other into a single pile, paying a cost equal to their combined weight; the goal is to keep merging until one pile remains, at the lowest total cost — or to recognize that ending on exactly one pile is impossible for this `n` and `k`, and report `-1`.
Reachability comes first: each merge trades `k` piles for `1`, shrinking the pile count by `k−1` every time, so the only counts ever reachable from `n` are `n, n−(k−1), n−2(k−1), …` — landing on 1 requires `(n−1)` to be a multiple of `(k−1)`, otherwise no sequence of moves ever finishes. Given that a solution exists, the same reachability rule applies to every sub-range too: split a range into two pieces at any point spaced `(k−1)` piles apart, solve each piece as its own smaller version of the problem, and whenever a range's own pile count can collapse to one, pay for that final merge by adding the range's total weight. Filling this in from short ranges up to the full array means every smaller answer a longer range needs has already been computed once.
Example 1:
Input: stones = [3,2,4,1], k = 2
Output: 20
Example 2:
Input: stones = [3,2,4,1], k = 3
Output: -1
Example 3:
Input: stones = [1], k = 3
Output: 0
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ stones.length ≤ 8 - ●
2 ≤ k ≤ stones.length - ●
1 ≤ stones[i] ≤ 100
stones =
[3, 2, 4, 1]
k =
2