Original link: leetcode-cn.com/problems/le…

Answer:

  1. First of all, let’s sort out the questions:
    • We only have five and ten dollars in change.
    • The question only cares about whether there is enough change, so you only need to consider the amount of change you received, not how much money you made.
  2. There are 3 possible scenarios for each receipt to simulate the change process:
    • If I make 5 dollars, I’m going to add 1 to my 5 dollars change.
    • If I get 10 dollars, I’m going to add 1 to my 10 dollar change and then I’m going to subtract 1 from my 5 dollar change.
    • If you have $20 and $5 change is more common, if you have $10 change you get $10 and $5 change. If you don’t have ten-yuan change, you get three five-yuan change.
  3. After each change is made, check whether the amount of change is negative, if not enough change, return false.
  4. If the loop can exit normally, that means the number of change is >=0, then return true.
/ * * *@param {number[]} bills
 * @return {boolean}* /
var lemonadeChange = function (bills) {
  let five = 0; // Count the change for 5 yuan
  let ten = 0; // Count the change for 10 yuan

  // Run through bills to simulate the process of collecting money
  for (const bill of bills) {
    if (bill === 5) {
      // If you receive 5 yuan, you only need to collect the money, no change is required. The amount of 5 yuan is increased by 1
      five++;
    } else if (bill === 10) {
      If 10 yuan is received, the amount of 10 yuan is increased by 1
      // You also need change of 5 yuan, which is reduced by 1
      ten++;
      five--;
    } else if (bill === 20) {
      // If you receive 20 yuan, you need change 15 yuan
      if (ten) {
        // If you have small change of 10 yuan, you can use 10 yuan first. The amount of 10 yuan is reduced by 1
        ten--;
        // After 10 yuan change, 5 yuan change is required, so the amount of 5 yuan is reduced by 1
        five--;
      } else {
        // If you don't have $10 change, use $5 change
        five -= 3; }}// If the amount of change is negative, there is not enough change to make change
    if (five < 0 || ten < 0) {
      return false; }}// If you can exit the loop normally, it means that the change is not negative and there is enough change
  return true;
};
Copy the code