Lemonade Change in Python


Suppose there is a lemonade stand, each lemonade costs $5. Now customers are standing in a queue to buy from the store, and order one at a time.

Each customer can buy only one lemonade and pay with either a $5, $10, or $20 bill. We have to must provide the correct change to each customer, so that the net transaction is that the customer pays $5. And at first, we have no change in hand.

We have to check whether we can provide every customer with correct change.

So, if the input is like [5,5,5,10,20], then the output will be True, as from the first 3 customers, we can get three $5 bills in order. From the fourth one, we collect a $10 bill and give back a $5. After that from the fifth customer, we give a $10 bill and a $5 bill. As all customers got correct change, we output true.

To solve this, we will follow these steps −

  • n5 := 0, n10 := 0, n20 := 0
  • for each i in bills, do
    • if i is same as 5, then
      • n5 := n5 + 1
    • otherwise when i is same as 10, then
      • n10 := n10 + 1
    • otherwise n20 := n20 + 1
    • if size of bills > 0 and n5 is same as 0, then
      • return False
    • if i is same as 20 and n10 > 0 and n5 > 0, then
      • n10 := n10 - 1
      • n5 := n5 - 1
    • Otherwise when i is same as 20 and n10 is same as 0 and n5 < 3, then
      • return False
    • otherwise when i is same as 20 and n10 is same as 0 and n5 >= 3, then
      • n5 := n5 -3
    • if i is same as 10 and n5 > 0, then
      • n5 := n5 - 1
    • otherwise when i is same as 10 and n5 is same as 0, then
      • return False
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def lemonadeChange(self, bills):
      n5 = 0
      n10 = 0
      n20 = 0
      for i in bills:
         if i == 5:
            n5 += 1
         elif i == 10:
            n10 += 1
         else:
            n20 += 1
         if len(bills) > 0 and n5 == 0:
            return(False)
         if i == 20 and n10 > 0 and n5 > 0:
            n10 -= 1
            n5 -= 1
         elif i == 20 and n10 == 0 and n5 < 3:
            return(False)
         elif i == 20 and n10 == 0 and n5 >= 3:
            n5 = n5 -3
         if i == 10 and n5 > 0:
            n5 -= 1
         elif i == 10 and n5 == 0:
            return (False)
      return(True)
ob = Solution()
print(ob.lemonadeChange([5,5,5,10,20]))

Input

[5,5,5,10,20]

Output

True

Updated on: 04-Jul-2020

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements