[코테 풀이] Lemonade Change

시내·2024년 6월 9일

Q_860) Lemonade Change

출처 : https://leetcode.com/problems/lemonade-change/?envType=study-plan-v2&envId=programming-skills

At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.

Note that you do not have any change in hand at first.

Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.

1st Try:

class Solution {
    public boolean lemonadeChange(int[] bills)  {
        int five = 0;
        int ten = 0;
        for (int i : bills) {
            if (i == 5) five++;
            else if (i == 10) {
                if (five >= 1) {
                    five--;
                    ten++;
                } else {
                    return false;
                }
            } else if (i == 20) {
                if (five >= 3) {
                    five -= 3;
                } else if (five >= 1 && ten >= 1) {
                    five--;
                    ten--;
                } else {
                    return false;
                }
            }
        }
        return true;
    }
}
  • 이 경우, $10는 있지만 $5가 없을 때,$10가 다른 거래 상황에서 사용될 수 있음에도 불구하고 바로 false를 return 해버린다.
  • else if(i==20) 구문에서의 ifelse if 조건의 순서를 바꿔줘야한다.

2nd Try:

class Solution {
    public boolean lemonadeChange(int[] bills)  {
        int five = 0;
        int ten = 0;
         for (int i : bills) {
            if (i == 5) five++;
            else if (i == 10) {
                if (five >= 1) {
                    five--;
                    ten++;
                } else {
                    return false;
                }
            } else if (i == 20) {
                if (five >= 1 && ten >= 1) {
                    five--;
                    ten--;
                } else if (five >= 3) {
                    five -= 3;
                } else {
                    return false;
                }
            }
        }
        return true;
    }
}

🙈 풀이 참조한 문제

profile
contact 📨 ksw08215@gmail.com

0개의 댓글