Leetcode 1774: Closest Dessert Cost

grid47
grid47
Exploring patterns and algorithms
May 13, 2024 7 min read

You are planning to make a custom dessert by choosing an ice cream base and toppings. The dessert must follow these rules: You must select one ice cream base. You can add one or more types of toppings, or choose to skip toppings. You can add at most two of each topping type. You are given an array representing the base costs and topping costs. The goal is to create a dessert where the total cost is as close as possible to the target price. If there are multiple dessert combinations that meet the target price, return the lower cost.
Problem
Approach
Steps
Complexity
Input: You are given three inputs:
Example: baseCosts = [2, 4], toppingCosts = [3, 5], target = 12
Constraints:
• 1 <= baseCosts.length, toppingCosts.length <= 10
• 1 <= baseCosts[i], toppingCosts[i] <= 10^4
• 1 <= target <= 10^4
Output: Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.
Example: Input: baseCosts = [2, 4], toppingCosts = [3, 5], target = 12, Output: 12
Constraints:
Goal: The goal is to find the combination of base and toppings that gives the closest cost to the target.
Steps:
• 1. Iterate through all the possible combinations of base and toppings (with up to two of each topping).
• 2. Calculate the cost for each combination.
• 3. Compare the cost to the target and track the closest possible cost.
• 4. If multiple combinations are equally close to the target, return the lower cost.
Goal: The constraints for this problem include the size and cost limits of the inputs.
Steps:
• 1 <= baseCosts.length, toppingCosts.length <= 10
• 1 <= baseCosts[i], toppingCosts[i] <= 10^4
• 1 <= target <= 10^4
Assumptions:
• You can choose any combination of base and toppings.
• There is no limit on the number of toppings you can choose, but no more than two of each topping type.
Input: Input: baseCosts = [2, 4], toppingCosts = [3, 5], target = 12
Explanation: By choosing base 1 (cost 4), topping 0 (1 x 3) and topping 1 (1 x 5), the total cost is exactly 12, which matches the target.

Input: Input: baseCosts = [1, 6], toppingCosts = [2, 4], target = 15
Explanation: By choosing base 1 (cost 6), topping 0 (1 x 2) and topping 1 (2 x 4), the total cost is 14, which is the closest value to 15.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus