Lemonade Change

Greedy — always return the largest bill first when making change.

Easy
Time O(n) Space O(1)
LeetCode
3 min read
greedy array

Problem#

Customers pay 5,5, 10, or 20fora20 for a 5 lemonade. You start with no change. Return true iff you can give exact change to every customer.

Examples#

  • [5,5,5,10,20]true.
  • [5,5,10,10,20]false.

Constraints#

  • 1 <= bills.length <= 10^5.

Approach#

Track counts of 5and5 and 10 bills. On 10:needa10: need a 5. On 20:preferone20: prefer one 10 + one 5;elsethree5; else three 5.

Solution#

Lemonade Change
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five = 0, ten = 0;
for (int b : bills) {
if (b == 5) ++five;
else if (b == 10) {
if (!five) return false;
--five; ++ten;
} else {
if (ten && five) { --ten; --five; }
else if (five >= 3) five -= 3;
else return false;
}
}
return true;
}
};

Editorial#

Preferring to give a 10whenpossiblepreservesthemoreflexible10 when possible preserves the more flexible 5s for cases that need them. This is the only safe choice — a 10isuselessforanynon10 is useless for any non-20 customer.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.