Algorithm/src/main/java/dynamic_programming/LastStoneWeightII.java

40 lines
1.5 KiB
Java
Raw Normal View History

2025-04-13 14:09:25 +08:00
package dynamic_programming;
import java.util.Arrays;
/**
* 题目 1049. 最后一块石头的重量 II (lastStoneWeightII)
* 描述有一堆石头用整数数组 stones 表示其中 stones[i] 表示第 i 块石头的重量
* 每一回合从中选出任意两块石头然后将它们一起粉碎假设石头的重量分别为 x y x <= y那么粉碎的可能结果如下
* 如果 x == y那么两块石头都会被完全粉碎
* 如果 x != y那么重量为 x 的石头将会完全粉碎而重量为 y 的石头新重量为 y-x
* 最后最多只会剩下一块 石头返回此石头 最小的可能重量 如果没有石头剩下就返回 0
示例 2
输入stones = [2,7,4,1,8,1]
输出1
解释
组合 2 4得到 2所以数组转化为 [2,7,1,8,1]
组合 7 8得到 1所以数组转化为 [2,1,1,1]
组合 2 1得到 1所以数组转化为 [1,1,1]
组合 1 1得到 0所以数组转化为 [1]这就是最优值
* 链接https://leetcode.cn/problems/last-stone-weight-ii/
*/
public class LastStoneWeightII {
public int lastStoneWeightII(int[] stones) {
int sum=0;
for (int stone : stones) {
sum+=stone;
}
int half=sum/2;
int[] dp=new int[half+1];
for (int stone : stones) {
for (int j = half; j >= stone; j--) {
dp[j] = Integer.max(dp[j], dp[j - stone] + stone);
}
}
return Math.abs(sum-2*dp[half]);
}
}