class Solution {
public int lastStoneWeightII(int[] stones) {
// S = S1 + S2, diff = S1 - S2, diff needs to be minimal, thus S - 2S2 will be minimal
int S = 0, s2 = 0;
for(int stone : stones) {
S += stone;
}
int len = stones.length;
boolean[][] dp = new boolean[S/2 + 1][len + 1]; // dp[s][i]: use stones from 0~i to construct sum s, if can construct then true else false
for(int i = 0; i <= len; i++) {
dp[0][i] = true;
}
for(int i = 1; i <= len; i++) {
for(int sum = 1; sum <= S/2; sum++){
int cur = stones[i - 1];
if (sum >= cur) {
dp[sum][i] = dp[sum - cur][i - 1] || dp[sum][i - 1];
} else {
dp[sum][i] = dp[sum][i - 1];
}
if(dp[sum][i]) {
s2 = Math.max(sum, s2);
}
}
}
return S - 2 * s2;
}
}
1046. Last Stone Weight
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> heap = new PriorityQueue(Collections.reverseOrder());
for(int each : stones)
heap.add(each);
while(heap.size() > 1) {
int top1 = heap.poll();
int top2 = heap.poll();
int diff = Math.abs(top1 - top2);
if(diff != 0) {
heap.add(diff);
}
}
if(heap.size() != 0) {
return heap.poll();
} else {
return 0;
}
}
}