Lemonade Change
买东西, 价值5块, 一共有三种货币5,10,20. 问能不能找开. 这个遇到20$先找大的($10 + $5), 再找小的($5 x 3).
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 31 |
class Solution { public boolean lemonadeChange(int[] bills) { int[] t = new int[2]; // t[0] = 5$, t[1] = 10$ for(int i = 0; i < bills.length; i++) { if(bills[i] == 5) t[0]++; else if(bills[i] == 10){ if(t[0] >= 1){ t[0]--; t[1]++; } else{ return false; } } else{ if(t[0] > 0 && t[1] > 0) { // 1 $10 + 1 $5 t[0] --; t[1] --; } else if(t[0] >= 3) { // 3 $5 t[0] -= 3; } else { return false; } } } return true; } } |