Number of Burgers with No Waste of Ingredients
Problem
You have tomatoSlices tomato slices and cheeseSlices cheese slices. A jumbo burger needs 4 tomato slices and 1 cheese slice; a small burger needs 2 tomato slices and 1 cheese slice. Return [jumbo, small] so that every slice is used up with no leftovers, or an empty list if no such counts exist.
tomatoSlices = 16, cheeseSlices = 7[1, 6]def num_of_burgers(tomato, cheese):
if tomato % 2 != 0:
return []
jumbo = (tomato - 2 * cheese) // 2
small = cheese - jumbo
if jumbo < 0 or small < 0:
return []
return [jumbo, small]
function numOfBurgers(tomato, cheese) {
if (tomato % 2 !== 0) return [];
const jumbo = (tomato - 2 * cheese) / 2;
const small = cheese - jumbo;
if (jumbo < 0 || small < 0) return [];
return [jumbo, small];
}
class Solution {
public List<Integer> numOfBurgers(int tomato, int cheese) {
if (tomato % 2 != 0) return new ArrayList<>();
int jumbo = (tomato - 2 * cheese) / 2;
int small = cheese - jumbo;
if (jumbo < 0 || small < 0) return new ArrayList<>();
return Arrays.asList(jumbo, small);
}
}
vector<int> numOfBurgers(int tomato, int cheese) {
if (tomato % 2 != 0) return {};
int jumbo = (tomato - 2 * cheese) / 2;
int small = cheese - jumbo;
if (jumbo < 0 || small < 0) return {};
return { jumbo, small };
}
Explanation
Let j be the number of jumbo burgers and s the number of small burgers. Every burger eats exactly one cheese slice, and a jumbo eats 4 tomato slices while a small eats 2. That gives a tidy pair of linear equations:
4j + 2s = tomatoSlices and j + s = cheeseSlices.
Multiply the second equation by 2 to get 2j + 2s = 2·cheeseSlices, then subtract it from the first. The 2s terms cancel and you are left with 2j = tomatoSlices − 2·cheeseSlices, so j = (tomatoSlices − 2·cheeseSlices) / 2. Once you know j, the second equation hands you s = cheeseSlices − j directly.
A clean answer only exists when the numbers line up: tomatoSlices must be even (otherwise the division leaves a half burger), and both j and s must be non-negative. If any of those checks fails, no valid combination uses up every slice, so we return an empty list.
Example: tomatoSlices = 16, cheeseSlices = 7. Then j = (16 − 14) / 2 = 1 and s = 7 − 1 = 6. Both are non-negative and 16 is even, so the answer is [1, 6].
Because everything is a handful of arithmetic operations, the whole thing runs in constant time with no loops at all.