1000. Minimum Cost to Merge Stones
SourceWeekly Contest 126 Q4DifficultyHardRating2422
Description
There are n piles of stones arranged in a row. The ith pile has stones[i] stones.
A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles.
Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], k = 2 Output: 20 Explanation: We start with [3, 2, 4, 1]. We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. We merge [4, 1] for a cost of 5, and we are left with [5, 5]. We merge [5, 5] for a cost of 10, and we are left with [10]. The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], k = 3 Output: -1 Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], k = 3 Output: 25 Explanation: We start with [3, 5, 1, 2, 6]. We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6]. We merge [3, 8, 6] for a cost of 17, and we are left with [17]. The total cost was 25, and this is the minimum possible.
Constraints:
n == stones.length1 <= n <= 301 <= stones[i] <= 1002 <= k <= 30
Solutions
Solution 1
Thinking
Enumerating every merge order is correct, but with \(n \le 30\) the number of valid partitions grows too quickly to search. Each move only merges \(K\) consecutive piles, so the cost is determined by subproblems of the form “turn a contiguous segment into a given number of piles,” and the same interval is reached by many orders.
Each merge reduces the pile count by \(K-1\), so a single pile exists only when \((n-1)\bmod (K-1)=0\); otherwise the answer is \(-1\). When it is feasible, merging \([i,j]\) into \(k\) piles means some prefix becomes \(1\) pile and the suffix becomes \(k-1\) piles; merging into \(1\) pile means first obtaining \(K\) piles and then paying the sum of that interval.
We therefore fill \(f[i][j][k]\) by increasing interval length and keep a prefix sum \(s\) for \(O(1)\) range sums. The split \(h\) always uses \(f[i][h][1]\) on the left, matching the consecutive-merge constraint. The answer is \(f[1][n][1]\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |