cs: add «860. Lemonade Change»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-15 11:05:00 +02:00
parent 9b4f9e0847
commit f57c9959f7
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

51
cs/lemonade-change.cs Normal file
View file

@ -0,0 +1,51 @@
public class Solution {
private enum Bill {
FIVE,
TEN,
TWENTY
}
private static Bill FromNumeric(int bill) => bill switch {
5 => Bill.FIVE,
10 => Bill.TEN,
20 => Bill.TWENTY,
_ => throw new ArgumentOutOfRangeException(nameof(bill), "Invalid bill"),
};
public bool LemonadeChange(int[] bills) {
var counters = new Dictionary<Bill, int> {
{ Bill.FIVE, 0 },
{ Bill.TEN, 0 },
{ Bill.TWENTY, 0 }
};
foreach (var numericBill in bills) {
var bill = FromNumeric(numericBill);
++counters[bill];
switch (bill) {
case Bill.FIVE:
/* no-op */
break;
case Bill.TEN:
if (counters[Bill.FIVE] <= 0) {
return false;
}
--counters[Bill.FIVE];
break;
case Bill.TWENTY:
if (counters[Bill.TEN] > 0 && counters[Bill.FIVE] > 0) {
--counters[Bill.FIVE];
--counters[Bill.TEN];
} else if (counters[Bill.FIVE] >= 3) {
counters[Bill.FIVE] -= 3;
} else {
return false;
}
break;
}
}
return true;
}
}