One, foreword
Change is generally greedy algorithm, local optimal is every change as far as possible to leave 5 yuan, local optimal results lead to the best.
2. Title Description
If the image above is fuzzy, look at itLeetcode topic link
Three, the analysis
- There are only three kinds of coins: 5, 10 and 20
- If you encounter five dollars, you don’t need change
- When you find 10 yuan, you have 5 yuan in your pocket. Pocket no 5 yuan, sorry, close the door we don’t sell
- When you encounter 20 yuan, you can’t open it if you don’t have 5 yuan in your pocket. If you have 10 yuan in your pocket and 5 yuan in it, use 10 yuan to find a 10 yuan and 5 yuan; If you only have five dollars in your pocket, but no more than three bills, sorry, close the door
Four, code,
Git code address
/** * title number: 860 * leetCode Address: https://leetcode-cn.com/problems/lemonade-change/ */ /** * @param {number[]} bills * @return {boolean} */ var LemonadeChange = function(bills) {// Let count5 = 0 let count10 = 0 for(const val of bills) { Count5 ++ if(val === 5) count5++ if(val === 10) {if(val === 1) return false Change the guest 5 yuan accept 10 yuan count5-- count10++} // meet 20 yuan, here greedy, first find 10 yuan then find 5 yuan. If (count5 < 1) return false if(count10) {// If (count10) {// If (count10) { Count5 -- count10--} else {if(count5 < 3) return false // Count5 < 3 Count5 -= 3}}} return true;Copy the code