Advertisement
ogv

Untitled

ogv
Aug 12th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. /*
  2. Runtime: 9 ms, faster than 84.83% of Java online submissions for Coin Change.
  3. Memory Usage: 35.8 MB, less than 97.63% of Java online submissions for Coin Change.
  4. */
  5. class Solution {
  6.     public int coinChange(int[] coins, int amount) {
  7.         if (coins.length == 0 ) return amount > 0 ? -1: 0;
  8.         if (amount == 0) return 0;
  9.              
  10.         int[] cache = new int[amount + 1];
  11.                
  12.         cache[0] = 0;
  13.        
  14.         for (int k = 0; k <= amount; k++) {
  15.             if (cache[k] <= 0 && k > 0) continue;            
  16.            
  17.             for (int i = 0; i < coins.length; i++) {
  18.                 int next = k + coins[i];
  19.                 if (next <= amount && next > 0) {
  20.                     int count = cache[k] + 1;
  21.  
  22.                     if (cache[next] <= 0 || cache[next] > count) {
  23.                         cache[next] = count;
  24.                     }
  25.                 }
  26.             }
  27.         }
  28.        
  29.         return cache[amount] > 0 ? cache[amount]: -1;
  30.     }    
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement