Maximum Number of Alloys — LeetCode 2861 Python Solution

MediumArrayBinary Search
Problem
#2861
Reading time
4 min

The problem

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.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times k \times \log M), where M is the upper bound of the binary search, and in this problem, M \leq 2 \times 10^8
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2861. Maximum Number of Alloys is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2861. Maximum Number of Alloys?
LeetCode 2861. Maximum Number of Alloys is rated Medium on LeetCode.
What is the time complexity of LeetCode 2861. Maximum Number of Alloys?
The Python solution on this page runs in O(n \times k \times \log M), where M is the upper bound of the binary search, and in this problem, M \leq 2 \times 10^8.
What is the space complexity of LeetCode 2861. Maximum Number of Alloys?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2861. Maximum Number of Alloys cover?
LeetCode 2861. Maximum Number of Alloys is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview