본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 860. Lemonade Change

반응형

https://leetcode.com/problems/lemonade-change/description/

 

Lemonade Change - LeetCode

Can you solve this real interview question? Lemonade Change - 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

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

5, 10, 20짜리 지폐의 개수를 저장할 변수 fiveBill, tenBill, twentyBill을 선언해 0으로 초기화해줍니다.

📔 풀이과정

bills정보에 대해 for loop를 수행합니다.

1. 5원을 지불했을때 거스름돈을 줄 필요가 없으므로 fiveBill을 1더해줍니다.

2.10원을 지불했을 때 5원을 거슬러줘야 하므로 줄 수 있다면 거슬러줍니다.

3. 20원일 때 15원을 거슬러줘야 하므로 줄 수 있다면 거슬러줍니다. 이 경우 15원을 거슬러줄 수 있는 방법이 5원 3장 또는 (5원 2, 10원 1장) 으로 2가지가 있으며 각 분기에 대해 거슬러줄 수 있다면 거슬러줍니다.

* 거슬러줄 수 없다면 false를 반환합니다.

* 각 지폐는 최소단위의 지폐로 분리할 수 없습니다. 20원을 받았다면 20원짜리 지폐 한 장이지 5원짜리 지폐4장으로 쪼개질 수 없습니다. 주의해 구현합니다.


📕 Code

📔 C++

class Solution {
public:
    bool lemonadeChange(vector<int>& bills) {
        int fiveBill = 0;
        int tenBill = 0;
        int twentyBill = 0;
        for(auto b : bills) {
            if (b == 5) fiveBill++;
            if (b == 10) {
                if(fiveBill < 1) return false;
                fiveBill--;
                tenBill++;
            }
            if (b == 20) {
                if(fiveBill >= 1 && tenBill >= 1) {
                    fiveBill -= 1;
                    tenBill -= 1;
                } else if (fiveBill >= 3) {
                    fiveBill -= 3;
                } else {
                    return false;
                }
            }
        }
        return true;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.