Number of Burgers with No Waste of Ingredients Problem
Description
LeetCode Problem 1276.
Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:
- Jumbo Burger:
4tomato slices and1cheese slice. - Small Burger:
2Tomato slices and1cheese slice.
Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].
Example 1:
Input: tomatoSlices = 16, cheeseSlices = 7
Output: [1,6]
Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.
There will be no remaining ingredients.
Example 2:
Input: tomatoSlices = 17, cheeseSlices = 4
Output: []
Explantion: There will be no way to use all ingredients to make small and jumbo burgers.
Example 3:
Input: tomatoSlices = 4, cheeseSlices = 17
Output: []
Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.
Constraints:
0 <= tomatoSlices, cheeseSlices <= 10^7
Solution
Approach: Solve Two Equations
Let jumbo and small be the numbers of burgers. Using every slice means
4 * jumbo + 2 * small = tomatoSlicesjumbo + small = cheeseSlices
Multiply the second equation by 4 and subtract the first: 2 * small = 4 * cheeseSlices - tomatoSlices. So small = (4 * cheeseSlices - tomatoSlices) / 2 and jumbo = cheeseSlices - small.
This pair is the only solution, so the answer exists exactly when it is made of whole, non-negative numbers:
4 * cheeseSlices - tomatoSlicesmust be even, orsmallis not an integer (for example17tomato slices: an odd number can never be used up, since each burger takes an even number);small >= 0(not too many tomato slices), andjumbo >= 0(not too few).
If any check fails, return []. With at most 10^7 slices, 4 * cheeseSlices stays below 2^31, so 32-bit integers are enough.
Complexity: O(1) time and space.
class Solution:
def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]:
# jumbo + small = cheeseSlices and 4 * jumbo + 2 * small = tomatoSlices
twice_small = 4 * cheeseSlices - tomatoSlices
small = twice_small // 2
jumbo = cheeseSlices - small
if twice_small % 2 != 0 or small < 0 or jumbo < 0:
return []
return [jumbo, small]