add: 柠檬水找零

This commit is contained in:
yi-ge 2020-05-24 23:46:31 +08:00
parent 8ca4a189f8
commit 06d357b002
3 changed files with 45 additions and 0 deletions

View File

@ -338,6 +338,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LintCode 1613. 最高频率的IP <https://www.lintcode.com/problem/highest-frequency-ip/description> - LintCode 1613. 最高频率的IP <https://www.lintcode.com/problem/highest-frequency-ip/description>
- [柠檬水找零](src/array/lemonade-change.js)
- LeetCode 860. 柠檬水找零 <https://leetcode-cn.com/problems/lemonade-change/>
- LintCode 1509. 柠檬水找零 <https://www.lintcode.com/problem/lemonade-change/description>
## 栈 ## 栈
- [最大矩阵](src/stack/maximal-rectangle.js) - [最大矩阵](src/stack/maximal-rectangle.js)

View File

@ -0,0 +1,31 @@
/**
* @param {number[]} bills
* @return {boolean}
*/
export const lemonadeChange = function (bills) {
const map = new Map()
while (bills.length) {
const money = bills.shift()
if (money === 5) {
map.set(5, (map.get(5) || 0) + 1)
} else {
let change = money - 5
while (change !== 0 && change - 10 > 0 && map.get(10) > 0) {
map.set(10, map.get(10) - 1)
change -= 10
}
while (change !== 0 && map.get(5) > 0) {
map.set(5, map.get(5) - 1)
change -= 5
}
if (change !== 0) return false
map.set(money, (map.get(money) || 0) + 1)
}
}
return true
}

View File

@ -0,0 +1,9 @@
import { lemonadeChange } from '../../src/array/lemonade-change'
test('柠檬水找零', () => {
expect(lemonadeChange([5, 5, 5, 5, 10, 5, 10, 10, 10, 20])).toBe(true)
expect(lemonadeChange([5, 5, 5, 10, 20])).toBe(true)
expect(lemonadeChange([5, 5, 10])).toBe(true)
expect(lemonadeChange([10, 10])).toBe(false)
expect(lemonadeChange([5, 5, 10, 10, 20])).toBe(false)
})