Leetcode Note: Go - Lemonade Change
Lemonade Change - LeetCode
https://leetcode.com/problems/lemonade-change/
- Go 言語で取り組んだメモ
所感
- int 配列 bills が渡される
- これには 5, 10, 20 の値が入っている
- すべての取引を行い釣り銭を提供できる場合には true を return する
回答
Lemonade Change - LeetCode
https://leetcode.com/problems/lemonade-change/solution/
GoLang Simple Solution. - LeetCode Discuss
https://leetcode.com/problems/lemonade-change/discuss/1096894/GoLang-Simple-Solution.
func lemonadeChange(bills []int) bool {
// define wallet
fivers := 0
teners := 0
twentiers := 0
// greedy
// give away change with largest bills possible
// if necessary bill doesn't exist, return false
for _, bill := range bills {
switch bill {
case 5:
fivers += 1
case 10:
if fivers >= 1 {
teners += 1
fivers -= 1
} else {
return false
}
case 20:
if (fivers >= 1) && (teners >= 1) {
twentiers += 1
teners -= 1
fivers -= 1
} else if fivers >= 3 {
twentiers += 1
fivers -= 3
} else {
return false
}
}
}
return true
}