Problem Description
Given n piles of stones arranged in a row where the i-th pile has stones[i] stones, a move consists of merging exactly k consecutive piles into one, and the cost to do so is the sum of the stones in these k piles. The goal is to merge all piles into a single pile with minimum cost; if it is impossible, return -1.
Key Insights
- You can only merge stones into one final pile if (n - 1) is divisible by (k - 1). If not, return -1.
- A dynamic programming approach is used where dp[i][j] represents the minimum cost to merge the subarray stones[i...j] into as few piles as possible.
- A prefix sum array is precomputed to quickly calculate the sum of stones in any subarray.
- When a segment can be merged into one pile (i.e. when (length - 1) % (k - 1) == 0), add the sum of stones in that segment to the dp value.
Space and Time Complexity
Time Complexity: O(n^3) due to the triple nested loop over segments and splits. Space Complexity: O(n^2) from the dp table and O(n) for the prefix sum array.
Solution
The problem is solved using a range DP approach. We first verify that merging all piles into one is feasible by checking if (n - 1) % (k - 1) == 0. Next, a prefix sum array is computed to optimize range sum calculations. A 2D dp table dp[i][j] is then used to store the minimum cost to merge stones[i...j]. For each interval, we consider valid split points, updating dp[i][j] by combining sub-problems. If the current segment can form a single merged pile (determined by the condition on the interval length), the cost of merging that segment (the sum of stones) is added to dp[i][j].