Statementâ–¼
There is a lemonade stand where customers can buy one lemonade at a time for
Given an integer array, bills
, where bills[i]
represents the bill paid by the
Constraints:
1≤ bills.length
≤500 bills[i]
is either5 ,10 , or20 .
Solution
The approach we will be using to solve this problem is the greedy approach. We have to make sure that for each transaction, we give a change to the customer if they provide us with a
To implement this, follow the steps below:
Create two variables,
fives
andtens
, to maintain the number of5 and10 bills.We iterate the bills array, and for each bill, we check the following conditions:
If the customer pays a
5 bill, we incrementfives
.If they pay a
10 bill, we check if we have a5 bill to provide as change. If yes, we decrementfives
and incrementtens
. Otherwise, we return FALSE.If the customer pays a
20 bill, we first proceed with the greedy approach by checking if we have10 and5 bills to provide as change. If yes, we decrementtens
andfives
. Otherwise, we check if we have three5 bills. If yes, we decrementfives
by3 . We return FALSE if we couldn’t provide the change to the customer in any way.
If the whole
bills
array has been processed, we know all customers have been provided with the lemonade and the correct change. Therefore, we return TRUE.
Let’s look at the illustration below for a better understanding: