Number of Burgers with No Waste of Ingredients

Problem Id: 1276 Difficulty: Medium Tag: Math Tag: Greedy


Intuition

This is basically a math problem.

Let's assume there are num_j of Jumbo and num_s of Small Burger. Based on the problem description.:

tomatoSlices = num_j * 4 + num_s * 2     (1)
cheeseSlices = num_j + num_s             (2)

By (1) - 2 * (2), we can get,:

num_j = (1 / 2) * tomatoSlices - cheeseSlices

By 4 * (2) - (1), we can get,:

num_s = 2 * cheeseSlices - tomatoSlices / 2

Finally, we need to check if num_j, num_s are valid. The solution is valid if and only if each is greater or equal than 0 and it is an integer.

Solution


class Solution:
    def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]:
        num_j = tomatoSlices / 2 - cheeseSlices
        num_s = 2 * cheeseSlices - tomatoSlices / 2

        if num_j < 0 or num_s < 0:
            return []
        if num_j != int(num_j) or num_s != int(num_s):
            return []
        return [int(num_j), int(num_s)]