Checking if change can be provided in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.

Let us consider the following situation:

A shopkeeper sells a single commodity which costs exactly ₹5. Some customers are standing in a queue and will purchase exactly one unit of this commodity each. The customers can provide the shopkeeper with a note of ₹5, ₹10 or ₹20. Considering that the shopkeeper has no money in the beginning and the array represents the notes given by the customers standing in the queue.

Our function should determine whether or not the shopkeeper can provide all the customers with exact changes.

For example, if the input to the function is

Input

const arr = [5, 5, 10, 10, 20];

Output

const output = false;

Output Explanation

Because the two 5 notes will be used to provide changes for two 10 notes and after that the changes for 20 note cannot be generated.

Following is the code:

Example

 Live Demo

const arr = [5, 5, 10, 10, 20];
const provideChanges = (arr = []) => {
   let fives = 0
   let tens = 0
   for(let i = 0; i < arr.length; i++) {
      switch(arr[i]) {
         case 5:
            fives += 1
            break
         case 10:
            if(fives <= 0) {
               return false
            }
            fives -= 1
            tens += 1
            break
         default:
            if(tens >= 1 && fives >= 1) {
            tens -= 1
            fives -= 1
         } else if(fives >= 3) {
            fives -= 3
         } else {
            return false
         }
         break
      }
   }
   return true
};
console.log(provideChanges(arr));

Output

false
raja
Published on 23-Apr-2021 11:15:04
Advertisements