Advertisement
Guest User

Grokking 235

a guest
Sep 29th, 2022
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. class Solution {
  2.     public int lastStoneWeightII(int[] stones) {
  3.         int n = stones.length;
  4.         int total = Arrays.stream(stones).sum();        
  5.         boolean[][] dp = new boolean[n + 1][total + 1];
  6.        
  7.         for (int i = 0; i <= n; i++) {
  8.             dp[i][0] = true;
  9.         }
  10.        
  11.         // Find all sums we can make from inputs
  12.         for (int i = 1; i <= n; i++) {
  13.             for (int sum = 1; sum <= total; sum++) {
  14.                 dp[i][sum] = dp[i - 1][sum];
  15.                 if (stones[i - 1] <= sum) {
  16.                     dp[i][sum] |= dp[i - 1][sum - stones[i - 1]];
  17.                 }
  18.             }
  19.         }
  20.        
  21.         /*
  22.           Find the minimum difference between 2 sums
  23.           Diff = leftSum - rightSum
  24.           Total = leftSum + rightSum
  25.                 = leftSum + leftSum - Diff
  26.        
  27.           => Diff = |Total - 2 * leftSum|        
  28.         */
  29.         int leftSum = 0;
  30.         for (int sum = 0; sum <= total / 2; sum++) {
  31.             if (dp[n][sum]) {
  32.                 leftSum = sum;
  33.             }
  34.         }
  35.        
  36.         return Math.abs(total - 2 * leftSum);
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement