[LeetCode] Maximum Number of Alloys

2861. Maximum Number of Alloys

You are the owner of a company that creates alloys using various types of metals. There are n different types of metals available, and you have access to k machines that can be used to create alloys. Each machine requires a specific amount of each metal type to create an alloy.

For the ith machine to create an alloy, it needs composition[i][j] units of metal of type j. Initially, you have stock[i] units of metal type i, and purchasing one unit of metal type i costs cost[i] coins.

Given integers n, k, budget, a 1-indexed 2D array composition, and 1-indexed arrays stock and cost, your goal is to maximize the number of alloys the company can create while staying within the budget of budget coins.

All alloys must be created with the same machine.

Return the maximum number of alloys that the company can create.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

class Solution {
bool search(int k, vector<int>& req, vector<int>& has, vector<int>& c, long long m) {
for(int i = 0; i < req.size(); i++) {
long long buy = max(0ll, 1ll * req[i] * m - has[i]);
if(buy * c[i] > k) return false;
k -= buy * c[i];
}
return k >= 0;
}
int helper(int k, vector<int>& req, vector<int>& has, vector<int>& c) {
long long l = 0, r = INT_MAX, res = 0;
while(l <= r) {
long long m = l + (r - l) / 2;
bool ok = search(k,req,has,c,m);
if(ok) {
res = max(res, m);
l = m + 1;
} else r = m - 1;
}
return res;
}
public:
int maxNumberOfAlloys(int n, int k, int budget, vector<vector<int>>& composition, vector<int>& stock, vector<int>& cost) {
int res = 0;
for(int i = 0; i < k; i++) {
res = max(res, helper(budget, composition[i], stock, cost));
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/17/PS/LeetCode/maximum-number-of-alloys/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.