#2861

Maximum Number of Alloys

Medium
ArrayBinary Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(1)
O(1)
💡

Intuition

Time O(n log m)Space O(1)

We can use binary search to efficiently find the maximum number of alloys we can create. By checking the feasibility of creating a certain number of alloys within the budget, we can narrow down our search space.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a function to check if a certain number of alloys can be created within the budget for a given machine.
  2. 2Step 2: Use binary search on the number of alloys from 0 to a large number (e.g., 10^6).
  3. 3Step 3: For each mid-point in the binary search, use the feasibility function to check if that many alloys can be created.
solution.py22 lines
1def canCreateAlloys(alloys, n, k, budget, composition, stock, cost):
2    for machine in range(k):
3        total_cost = 0
4        for metal in range(n):
5            required = composition[machine][metal] * alloys - stock[metal]
6            if required > 0:
7                total_cost += required * cost[metal]
8        if total_cost <= budget:
9            return True
10    return False
11
12def maxAlloys(n, k, budget, composition, stock, cost):
13    left, right = 0, 10**6
14    max_alloys = 0
15    while left <= right:
16        mid = (left + right) // 2
17        if canCreateAlloys(mid, n, k, budget, composition, stock, cost):
18            max_alloys = mid
19            left = mid + 1
20        else:
21            right = mid - 1
22    return max_alloys

Complexity note: The time complexity is O(n log m) where n is the number of metals and m is the maximum number of alloys we are checking. The log m comes from the binary search over the number of alloys.

  • 1Binary search can significantly reduce the number of checks needed.
  • 2Feasibility checking is a common pattern in optimization problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.