java.lang.Object
g0901_1000.s1000_minimum_cost_to_merge_stones.Solution

public class Solution extends Object
1000 - Minimum Cost to Merge Stones.<p>Hard</p> <p>There are <code>n</code> piles of <code>stones</code> arranged in a row. The <code>i<sup>th</sup></code> pile has <code>stones[i]</code> stones.</p> <p>A move consists of merging exactly <code>k</code> consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these <code>k</code> piles.</p> <p>Return <em>the minimum cost to merge all piles of stones into one pile</em>. If it is impossible, return <code>-1</code>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> stones = [3,2,4,1], k = 2</p> <p><strong>Output:</strong> 20</p> <p><strong>Explanation:</strong> We start with [3, 2, 4, 1].</p> <p>We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].</p> <p>We merge [4, 1] for a cost of 5, and we are left with [5, 5].</p> <p>We merge [5, 5] for a cost of 10, and we are left with [10].</p> <p>The total cost was 20, and this is the minimum possible.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> stones = [3,2,4,1], k = 3</p> <p><strong>Output:</strong> -1</p> <p><strong>Explanation:</strong> After any merge operation, there are 2 piles left, and we can&rsquo;t merge anymore. So the task is impossible.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> stones = [3,5,1,2,6], k = 3</p> <p><strong>Output:</strong> 25</p> <p><strong>Explanation:</strong> We start with [3, 5, 1, 2, 6].</p> <p>We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].</p> <p>We merge [3, 8, 6] for a cost of 17, and we are left with [17].</p> <p>The total cost was 25, and this is the minimum possible.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == stones.length</code></li> <li><code>1 <= n <= 30</code></li> <li><code>1 <= stones[i] <= 100</code></li> <li><code>2 <= k <= 30</code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • mergeStones

      public int mergeStones(int[] stones, int k)