Maximum Number of Alloys - Binary Search [JS]

Description 

Solution: Binary Search

Binary search for the maixmum number of alloys.
To check whether a number of alloys x is viable,
go through each machine and check whether it's possible to create x alloys based on the compositionstockcost, and budget.

k = number of machinesn = number of metalsm = max possible alloys (max(stocks[i]) + budget)
Time Complexity: O(kn log(m))
Space Complexity: O(1)

var maxNumberOfAlloys = function(n, k, budget, composition, stock, cost) {
  let maxStock = Math.max(...stock) + budget;
  let low = 0, high = maxStock;
  while (low < high) {
    let mid = Math.ceil((low + high) / 2);
    if (isPossible(n, k, budget, composition, stock, cost, mid)) low = mid;
    else high = mid - 1;
  }
  return low;
};

function isPossible(n, k, budget, composition, stock, cost, alloys) {
  for (let i = 0; i < k; i++) {
    let budgetUsed = 0, machineCanHandle = true;
    for (let j = 0; j < n; j++) {
      let need = Math.max(composition[i][j] * alloys, stock[j]) - (stock[j]);
      let currCost = need * cost[j];
      if (budgetUsed + currCost > budget) {
        machineCanHandle = false;
        break;
      }
      budgetUsed += currCost;
    }
    if (machineCanHandle) return true;
  }
  return false;
}

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]