当前位置:网站首页>LeetCode 1049. 最后一块石头的重量 II 每日一题
LeetCode 1049. 最后一块石头的重量 II 每日一题
2022-07-07 15:32:00 【@小红花】
问题描述
有一堆石头,用整数数组 stones 表示。其中 stones[i] 表示第 i 块石头的重量。
每一回合,从中选出任意两块石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:
如果 x == y,那么两块石头都会被完全粉碎;
如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
最后,最多只会剩下一块 石头。返回此石头 最小的可能重量 。如果没有石头剩下,就返回 0。示例 1:
输入: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],这就是最优值。
示例 2:输入:stones = [31,26,33,21,40]
输出:5
提示:
1 <= stones.length <= 30
1 <= stones[i] <= 100来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/last-stone-weight-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public int lastStoneWeightII(int[] stones) {
int n = stones.length;
int sum = 0;
for(int i : stones){
sum += i;
}
int[] dp = new int[sum / 2 + 1];
for(int i = 0;i < n;i++){
for(int j = sum / 2;j >= stones[i];j--){
dp[j] = Math.max(dp[j],dp[j - stones[i]] + stones[i]);
}
}
return sum - dp[sum / 2] * 2;
}
}边栏推荐
猜你喜欢

Master this set of refined Android advanced interview questions analysis, oppoandroid interview questions

记一次项目的迁移过程

【C 语言】 题集 of Ⅹ

记录Servlet学习时的一次乱码

如何快速检查钢网开口面积比是否符合 IPC7525

运算符

【DesignMode】外观模式 (facade patterns)

1亿单身男女“在线相亲”,撑起130亿IPO

The difference and working principle between compiler and interpreter
最新高频Android面试题目分享,带你一起探究Android事件分发机制
随机推荐
Cesium(3):ThirdParty/zip. js
Build an all in one application development platform, light flow, and establish a code free industry benchmark
直接上干货,100%好评
[summary of knowledge] summary of notes on using SVN in PHP
【HCSD大咖直播】亲授大厂面试秘诀-简要笔记
【DesignMode】模板方法模式(Template method pattern)
23. 合并K个升序链表-c语言
ATM系统
LocalStorage和SessionStorage
Laravel constructor and middleware execution order
Temperature sensor chip used in temperature detector
面试题 01.02. 判定是否互为字符重排-辅助数组算法
Three. JS series (2): API structure diagram-2
ATM system
As an Android Developer programmer, Android advanced interview
Laravel post shows an exception when submitting data
编程模式-表驱动编程
The team of East China Normal University proposed the systematic molecular implementation of convolutional neural network with DNA regulation circuit
如何快速检查钢网开口面积比是否符合 IPC7525
[medical segmentation] attention Unet