Maximum Number of Alloys - Binary Search [JS]
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 composition
, stock
, cost
, and budget
.
k = number of machines
, n = number of metals
, m = 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
Post a Comment