Closest Dessert Cost

You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert:

  • There must be exactly one ice cream base.
  • You can add one or more types of topping or have no toppings at all.
  • There are at most two of each type of topping.

You are given three inputs:

  • baseCosts, an integer array of length n, where each baseCosts[i] represents the price of the ith ice cream base flavor.
  • toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the ith topping.
  • target, an integer representing your target price for dessert.

You want to make a dessert with a total cost as close to target as possible.

Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.

Example 1:

Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10
Output: 10
Explanation: Consider the following combination (all 0-indexed):
- Choose base 1: cost 7
- Take 1 of topping 0: cost 1 x 3 = 3
- Take 0 of topping 1: cost 0 x 4 = 0
Total: 7 + 3 + 0 = 10.

思路:注意题目意思是,每种topping最多只能要两个,种类不限制,那么就是每种有0,1,2三种选择;两种choice update res,一种是跟taret的绝对值小于res, 另外一种是相等的话,cursum < res;

class Solution {
    public int closestCost(int[] baseCosts, int[] toppingCosts, int target) {
        int[] res = new int[]{Integer.MAX_VALUE};
        for(int i = 0; i < baseCosts.length; i++) {
            dfs(baseCosts[i], target, toppingCosts, 0, res);
        }
        return res[0];
    }
    
    private void dfs(int cursum, int target, int[] toppingCosts, int index, int[] res) {
        if(Math.abs(target - cursum) < Math.abs(target - res[0]) ||
          (Math.abs(target - cursum) == Math.abs(target - res[0]) && cursum < res[0])) {
            res[0] = cursum;
        }
        if(index == toppingCosts.length || cursum > target) {
            return;
        }
        dfs(cursum, target, toppingCosts, index + 1, res);
        dfs(cursum + toppingCosts[index], target, toppingCosts, index + 1, res);
        dfs(cursum + 2 * toppingCosts[index], target, toppingCosts, index + 1, res);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值