tickets.js

Codewars 알고리즘 풀이


Problem

  • The new movie has just been released.
    • 새로운 영화가 방금 출시되었다.
  • There are a lot of people at the cinema box office standing in a huge line.
    • 시네마 박스 오피스에는 수많은 사람들이 줄 서 있다.
  • Each of them has a single ‘100’, ‘50’ or ‘25’ dollar bill.
    • 각각 100, 50, 25달러짜리 지폐를 가지고 있다.
  • Sam is currently working as a clerk.
    • Sam은 사원으로 일하고 있다.
  • He wants to sell a ticket to every single person in this line.
    • 그는 이 줄에 있는 모든 사람에게 티켓을 판매하려고 한다.
  • Can Sam sell a ticket to every single person and give change if he initially has no money and sells the tickets strictly in the order people queue?
    • Sam은 처음에 돈이 없고, 대기열에 있는 모든 사람에게 티켓을 정확히 판매할 수 있는지를 반환한다.



Solution 01

function tickets(arr) {
  let bills = [0, 0, 0];
  
  for (let i = 0; i < arr.length; i++) {
    switch (arr[i]) {
      case 25:
        bills[0]++;
        break;
      case 50:
        bills[0]--;
        bills[1]++;
        break;
      case 100:
        bills[1] ? bills[1]-- : (bills[0] -= 2);
        bills[0]--;
        break;
    }
    
    if (bills[0] < 0) {
      return 'NO';
    }
  }
  return 'YES';
}

tickets([50]);               // NO
tickets([25]);               // YES
tickets([25, 50]);           // YES
tickets([25, 50, 50]);       // NO
tickets([25, 100]);          // NO
tickets([25, 25, 100]);      // NO
tickets([25, 25, 25, 100]);  // YES
tickets([25, 25, 50, 100]);  // YES


Solution 02

function tickets(arr) {
  let [b25, b50, b100] = [0, 0, 0];
  
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 25) {
      b25++;
    }
    
    if (arr[i] === 50) {
      b50++;
      b25--;
    }
    
    if (arr[i] === 100) {
      b25--;
      b50 > 0 ? b50-- : (b25 -= 2);
    }
    
    if (b25 < 0 || b50 < 0) return 'NO';
  }
  return 'YES';
}

tickets([50]);               // NO
tickets([25]);               // YES
tickets([25, 50]);           // YES
tickets([25, 50, 50]);       // NO
tickets([25, 100]);          // NO
tickets([25, 25, 100]);      // NO
tickets([25, 25, 25, 100]);  // YES
tickets([25, 25, 50, 100]);  // YES