rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

1049. 最后一块石头的重量 II #118

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
class Solution {
    public int lastStoneWeightII(int[] stones) {
        int total = 0;
        for (int stone : stones) {
            total += stone;
        }
        int target = total/2;
        int[][] dp = new int[stones.length][target+1];
        for (int i = stones[0]; i <= target; i++) {
            dp[0][i] = stones[0];
        }
        for (int i = 1; i < stones.length; i++){
            for (int j = 1; j <= target; j++) {
                if (j >= stones[i]){
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - stones[i]] + stones[i]);
                }else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }

        return total - 2 * dp[stones.length-1][target];
    }
}