At a lemonade stand, each lemonade costs
Customers are standing in a queue to buy from you, and order one at a time (in the order specified by
Each customer will only buy one lemonade and pay with either a
Note that you don't have any change in hand at first
$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 don't have any change in hand at first
Example 1:
Input: [5,5,5,10,20]
Output: true
Approach
Java
public class LemonadeChange {public static void main(String[] args) {int arr[] = { 5, 5, 5, 10, 20 };System.out.println(lemonadeChange(arr));}// function to check for// lemando changestatic boolean lemonadeChange(int[] bills) {int cnt5 = 0, cnt10 = 0;int flag = 0;for (int i = 0; i < bills.length; i++) {if (bills[i] == 5)cnt5++;else if (bills[i] == 10) {if (cnt5 == 0) {flag = 1;break;} else {cnt5--;cnt10++;}} else if (bills[i] == 20) {if (cnt5 == 0) {flag = 1;break;} else if (cnt10 == 0 && cnt5 < 3) {flag = 1;break;} else if (cnt10 == 0) {cnt5 -= 3;} else if (cnt10 > 0) {cnt10--;cnt5--;}}}if (flag == 0)return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check for//lemando changebool lemonadeChange(vector<int>& bills){int cnt5=0,cnt10=0;int flag=0;for(int i=0;i<bills.size();i++){if(bills[i]==5)cnt5++;else if(bills[i]==10){if(cnt5==0){flag=1;break;}else{cnt5--;cnt10++;}}else if(bills[i]==20){if(cnt5==0){flag=1;break;}else if(cnt10==0 &&cnt5<3){flag=1;break;}else if(cnt10==0){cnt5-=3;}else if(cnt10>0){cnt10--;cnt5--;}}}if(flag==0)return true;return false;}int main(){vector<int> arr={5,5,5,10,20};if(lemonadeChange(arr))cout<<"true";elsecout<<"false";return 0;}
No comments:
Post a Comment