Problem
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:
1 | Input: tomatoSlices = 16, cheeseSlices = 7 |
Example 2:
1 | Input: tomatoSlices = 17, cheeseSlices = 4 |
Example 3:
1 | Input: tomatoSlices = 4, cheeseSlices = 17 |
Constraints:
0 <= tomatoSlices, cheeseSlices <= 107
Analysis
这道题目的背景是做汉堡,有两种汉堡,Jumbo Burger要4片tomato和1片cheese,Small Burger要2片tomato和1片cheese,题目给出了tomatoSlices和cheeseSlices的数量,问两种汉堡最多能做多少个,其中要求两种材料都没有剩余,如果做不到则返回空。
这个问题一下子好像很困难,但是两个变量,去组成两种汉堡,这个听起来很小小学的方程题目啊,再仔细一看这不就是鸡兔同笼问题吗。先列方程,假设能做x个Jumbo Burger,能做y个Small Burger,那么有4x + 2y = tomatoSlices,x + y = cheeseSlices。然后我们来看怎么判断能否做到。
先消元y,得到2x = tomatoSlices - 2cheeseSlices,所以这里要保证tomatoSlices >= 2 * chessSlices,因为要求解x,所以tomatoSlices % 2 == 0才能保证x有整数解。求解完x后代入计算y,2y = 4cheeseSlices - tomatoSlices,同理要保证4 * cheesseSlices >= tomatoSlices。因为要求解y,所以tomatoSlices % 2 == 0才能保证y有整数解。
把上面的条件都判断一遍,如果都满足要求就直接代入方程计算出x和y,否则就返回空。
Solution
无。
Code
1 | class Solution { |
Summary
这道题目实际上就是一道数学题,在解方程的过程中需要注意合法的情况,保证大于0以及保证整数解。这道题目的分享到这里,感谢你的支持!