1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public int lastStoneWeightII(int[] stones) { int n = stones.length; int sum = 0; for(int i = 0; i < n; i++){ sum += stones[i]; }
int neg = sum/2; boolean[][] dp = new boolean[n+1][neg+1]; dp[0][0] = true; for(int i = 1; i <= n; i++){ for(int j = 0; j <= neg; j++){ dp[i][j] = dp[i-1][j]; if(j >= stones[i-1]){ dp[i][j] = dp[i-1][j] || dp[i-1][j-stones[i-1]]; } } }
for(int j = neg; j >= 0; j--){ if(dp[n][j]){ return sum - 2*j; } } return 0; } }
|