DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Buy Maximum Items with Given Sum

The problem of buying the maximum items with a given sum.

Given an array cost of items & sum is max amount you have.

var maximumItemToBuy = function (cost, sum) {
  const Q = new MinPriorityQueue();
  for (let i = 0; i < cost.length; i++) {
    Q.enqueue(cost[i]);
  }

  let res = 0;
  while (true) {
    let popedElement = cost.dequeue().element;
    if (sum > popedElement) {
      sum = sum - popedElement;
      res++;
    } else {
      break;
    }
  }
  return res;
};

console.log(maximumItemToBuy([1,5,11,120,200], 10)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)