[LeetCode] 1000. Minimum Cost to Merge Stones

There are N piles of stones arranged in a row.  The i-th pile has stones[i] stones.

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.

Find 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.

Note:

  • 1 <= stones.length <= 30
  • 2 <= K <= 30
  • 1 <= stones[i] <= 100
class Solution {
    private Integer[][][] dp;
    private int[] prefixSum;
    public int mergeStones(int[] stones, int K) {
        int n = stones.length;
        dp = new Integer[n][n][K + 1];
        for(int i = 0; i < n; i++) {
            dp[i][i][1] = 0;
        }
        prefixSum = new int[n + 1];
        for(int i = 1; i <= n; i++){
            prefixSum[i] = prefixSum[i - 1] + stones[i - 1];
        }
        int res = merge(stones, 0, n - 1, 1, K);
        return res == Integer.MAX_VALUE ? -1 : res;
    }
    private int merge(int[] stones, int start, int end, int numOfPiles, int K) {
        if((end - start + 1 - numOfPiles) % (K - 1) != 0) {
            return Integer.MAX_VALUE;
        }
        if(dp[start][end][numOfPiles] != null) {
            return dp[start][end][numOfPiles];
        }
        int minCost = Integer.MAX_VALUE;
        if(numOfPiles == 1) {
            int mergeCost = merge(stones, start, end, K, K);
            if(mergeCost != Integer.MAX_VALUE) {
                minCost = mergeCost + prefixSum[end + 1] - prefixSum[start];
            }
        }
        else {
            for(int mid = start; mid < end; mid++) {
                int leftMergeCost = merge(stones, start, mid, 1, K);
                if(leftMergeCost == Integer.MAX_VALUE) {
                    continue;
                }
                int rightMergeCost = merge(stones, mid + 1, end, numOfPiles - 1, K);
                if(rightMergeCost == Integer.MAX_VALUE) {
                    continue;
                }
                minCost = Math.min(minCost, leftMergeCost + rightMergeCost);
            }
        }
        dp[start][end][numOfPiles] = minCost;
        return minCost;
    }
}

Related Problems

Stone Game (A special case of K == 2)

原文地址:https://www.cnblogs.com/lz87/p/10468623.html

时间: 2024-11-08 08:00:07

[LeetCode] 1000. Minimum Cost to Merge Stones的相关文章

[LeetCode 1368] Minimum Cost to Make at Least One Valid Path in a Grid

Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 

[LeetCode] 857. Minimum Cost to Hire K Workers 雇佣K名工人的最低成本

There are?N?workers.? The?i-th worker has a?quality[i]?and a minimum wage expectation?wage[i]. Now we want to hire exactly?K?workers to form a?paid group.? When hiring a group of K workers, we must pay them according to the following rules: Every wor

LeetCode 857. Minimum Cost to Hire K Workers

合法的pay group里所有worker的比例是一样的,即 wage1/wage2 = quality1/quality2 推出 wage1/quality1 = wage2/quality2. 这就好办了,定义 ratio_i = wage_i/quality_i.对于一个group,ratio一定是所有人中最大的那个. 对于一个大小为k的group,需要pay的钱就是 Σ_k quality_i * 最大的ratio. 为了避免每次扫一遍group找到最大的ratio,我们根据ratio排

LeetCode --- 64. Minimum Path Sum

题目链接:Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 这道题的要求是在m*n

【Leetcode】Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 思路:简单的动态规划题目,设f(m, n)为从(0, 0)到达(m

【leetcode】Minimum Window Substring

问题: 给定两个字符串,S,T,返回S中包含T中所有字符的最短的字串,若不存在,则返回"".时间复杂度为O(n). 例如:S = "ADOBCODEBANC" T = "ABC" 返回BANC 生活场景: 把问题具体化现实化一点.有n层楼,每层楼里放有一个物品,现在老板给你一个物品清单,里面是要你集齐的物品,你可以乘坐电梯,但是电梯只停一次,停在哪一层,就从哪一层开始向楼上搜集物品,至于要在那层停电梯,由你自己选择. 这里我们当然选择即能集齐物品

POJ 2516 Minimum Cost(最小费用最大流啊)

题目链接:http://poj.org/problem?id=2516 Description Dearboy, a goods victualer, now comes to a big problem, and he needs your help. In his sale area there are N shopkeepers (marked from 1 to N) which stocks goods from him.Dearboy has M supply places (mar

POJ 2516 Minimum Cost (最小费用最大流)

POJ 2516 Minimum Cost 链接:http://poj.org/problem?id=2516 题意:有M个仓库,N个商人,K种物品.先输入N,M,K.然后输入N行K个数,每一行代表一个商人要购买的物品,其中K个数分别表示要购买的每件商品数.然后是M行K个数,每行表示仓库里的情况,其中K个数分别每种物品的库存量.接下来是K个矩阵,每个矩阵为N*M,分别表示第K种物品从M个仓库运到第N个商人的花费.问能否合理安排,使得花费最少,如果不行就输出-1. 思路: 一开始的时候,竟然构造了

POJ 2516 Minimum Cost

Minimum Cost Time Limit: 4000ms Memory Limit: 65536KB This problem will be judged on PKU. Original ID: 251664-bit integer IO format: %lld      Java class name: Main Dearboy, a goods victualer, now comes to a big problem, and he needs your help. In hi