Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,0], cost = [1,2,3] Output: 2 Explanation: It is optimal to use the 1st machine to create alloys. To create 2 alloys we need to buy the: - 2 units of metal of the 1st type. - 2 units of metal of the 2nd type. - 2 units of metal of the 3rd type. In total, we need 2 * 1 + 2 * 2 + 2 * 3 = 12 coins, which is smaller than or equal to budget = 15. Notice that we have 0 units of metal of each type and we have to buy all the required units of metal. It can be proven that we can create at most 2 alloys.
Example 2:
Input: n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,100], cost = [1,2,3] Output: 5 Explanation: It is optimal to use the 2nd machine to create alloys. To create 5 alloys we need to buy: - 5 units of metal of the 1st type. - 5 units of metal of the 2nd type. - 0 units of metal of the 3rd type. In total, we need 5 * 1 + 5 * 2 + 0 * 3 = 15 coins, which is smaller than or equal to budget = 15. It can be proven that we can create at most 5 alloys.
Example 3:
Input: n = 2, k = 3, budget = 10, composition = [[2,1],[1,2],[1,1]], stock = [1,1], cost = [5,5] Output: 2 Explanation: It is optimal to use the 3rd machine to create alloys. To create 2 alloys we need to buy the: - 1 unit of metal of the 1st type. - 1 unit of metal of the 2nd type. In total, we need 1 * 5 + 1 * 5 = 10 coins, which is smaller than or equal to budget = 10. It can be proven that we can create at most 2 alloys.
Constraints:
1 <= n, k <= 1000 <= budget <= 108composition.length == kcomposition[i].length == n1 <= composition[i][j] <= 100stock.length == cost.length == n0 <= stock[i] <= 1081 <= cost[i] <= 100Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search
3 2 15 [[1,1,1],[1,1,10]] [0,0,0] [1,2,3]
3 2 15 [[1,1,1],[1,1,10]] [0,0,100] [1,2,3]
2 3 10 [[2,1],[1,2],[1,1]] [1,1] [5,5]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2861: Maximum Number of Alloys
class Solution {
int n;
int budget;
List<List<Integer>> composition;
List<Integer> stock;
List<Integer> cost;
boolean isValid(long target) {
for (List<Integer> currMachine : composition) {
long remain = budget;
for (int j = 0; j < n && remain >= 0; j++) {
long need = Math.max(0, currMachine.get(j) * target - stock.get(j));
remain -= need * cost.get(j);
}
if (remain >= 0) {
return true;
}
}
return false;
}
public int maxNumberOfAlloys(int n, int k, int budget, List<List<Integer>> composition,
List<Integer> stock, List<Integer> cost) {
this.n = n;
this.budget = budget;
this.composition = composition;
this.stock = stock;
this.cost = cost;
int l = -1;
int r = budget / cost.get(0) + stock.get(0);
while (l < r) {
int mid = (l + r + 1) >> 1;
if (isValid(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
}
// Accepted solution for LeetCode #2861: Maximum Number of Alloys
func maxNumberOfAlloys(n int, k int, budget int, composition [][]int, stock []int, cost []int) int {
isValid := func(target int) bool {
for _, currMachine := range composition {
remain := budget
for i, x := range currMachine {
need := max(0, x*target-stock[i])
remain -= need * cost[i]
}
if remain >= 0 {
return true
}
}
return false
}
l, r := 0, budget+stock[0]
for l < r {
mid := (l + r + 1) >> 1
if isValid(mid) {
l = mid
} else {
r = mid - 1
}
}
return l
}
# Accepted solution for LeetCode #2861: Maximum Number of Alloys
class Solution:
def maxNumberOfAlloys(
self,
n: int,
k: int,
budget: int,
composition: List[List[int]],
stock: List[int],
cost: List[int],
) -> int:
ans = 0
for c in composition:
l, r = 0, budget + stock[0]
while l < r:
mid = (l + r + 1) >> 1
s = sum(max(0, mid * x - y) * z for x, y, z in zip(c, stock, cost))
if s <= budget:
l = mid
else:
r = mid - 1
ans = max(ans, l)
return ans
// Accepted solution for LeetCode #2861: Maximum Number of Alloys
/**
* [2861] Maximum Number of Alloys
*/
pub struct Solution {}
// submission codes start here
impl Solution {
fn check(
n: usize,
count: i32,
budget: i32,
composition: &Vec<i32>,
stock: &Vec<i32>,
cost: &Vec<i32>,
) -> bool {
let mut need = 0i64;
for i in 0..n {
let number = composition[i] * count - stock[i];
if number > 0 {
need += number as i64 * cost[i] as i64;
}
}
need <= budget as i64
}
pub fn max_number_of_alloys(
n: i32,
k: i32,
budget: i32,
composition: Vec<Vec<i32>>,
stock: Vec<i32>,
cost: Vec<i32>,
) -> i32 {
let mut result = 0;
let (n, k) = (n as usize, k as usize);
for m in 0..k {
let mut left = 0;
let mut right = vec![0; n];
for i in 0..n {
right[i] = (stock[i] + budget / cost[i]) / composition[m][i];
}
let mut right = *right.iter().max().unwrap();
while left < right {
let mid = (left + right) / 2;
if Solution::check(n, mid, budget, &composition[m], &stock, &cost) {
left = mid + 1;
} else {
right = mid;
}
dbg!(left, right);
}
if !Solution::check(n, left, budget, &composition[m], &stock, &cost) {
left = left - 1;
}
result = result.max(left);
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2861() {
assert_eq!(
Solution::max_number_of_alloys(
3,
2,
15,
vec![vec![1, 1, 1], vec![1, 1, 10]],
vec![0, 0, 0],
vec![1, 2, 3]
),
2
);
}
}
// Accepted solution for LeetCode #2861: Maximum Number of Alloys
function maxNumberOfAlloys(
n: number,
k: number,
budget: number,
composition: number[][],
stock: number[],
cost: number[],
): number {
let l = 0;
let r = budget + stock[0];
const isValid = (target: number): boolean => {
for (const currMachine of composition) {
let remain = budget;
for (let i = 0; i < n; ++i) {
let need = Math.max(0, target * currMachine[i] - stock[i]);
remain -= need * cost[i];
}
if (remain >= 0) {
return true;
}
}
return false;
};
while (l < r) {
const mid = (l + r + 1) >> 1;
if (isValid(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.