1774. Closest Dessert Cost Medium

@problem@discussion
#Array#Dynamic Programming#Backtracking



1/**
2 * [1774] Closest Dessert Cost
3 *
4 * 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:
5 * 
6 * 	There must be exactly one ice cream base.
7 * 	You can add one or more types of topping or have no toppings at all.
8 * 	There are at most two of each type of topping.
9 * 
10 * You are given three inputs:
11 * 
12 * 	baseCosts, an integer array of length n, where each baseCosts[i] represents the price of the i^th ice cream base flavor.
13 * 	toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the i^th topping.
14 * 	target, an integer representing your target price for dessert.
15 * 
16 * You want to make a dessert with a total cost as close to target as possible.
17 * Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.
18 *  
19 * Example 1:
20 * 
21 * Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10
22 * Output: 10
23 * Explanation: Consider the following combination (all 0-indexed):
24 * - Choose base 1: cost 7
25 * - Take 1 of topping 0: cost 1 x 3 = 3
26 * - Take 0 of topping 1: cost 0 x 4 = 0
27 * Total: 7 + 3 + 0 = 10.
28 * 
29 * Example 2:
30 * 
31 * Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18
32 * Output: 17
33 * Explanation: Consider the following combination (all 0-indexed):
34 * - Choose base 1: cost 3
35 * - Take 1 of topping 0: cost 1 x 4 = 4
36 * - Take 2 of topping 1: cost 2 x 5 = 10
37 * - Take 0 of topping 2: cost 0 x 100 = 0
38 * Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.
39 * 
40 * Example 3:
41 * 
42 * Input: baseCosts = [3,10], toppingCosts = [2,5], target = 9
43 * Output: 8
44 * Explanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.
45 * 
46 *  
47 * Constraints:
48 * 
49 * 	n == baseCosts.length
50 * 	m == toppingCosts.length
51 * 	1 <= n, m <= 10
52 * 	1 <= baseCosts[i], toppingCosts[i] <= 10^4
53 * 	1 <= target <= 10^4
54 * 
55 */
56pub struct Solution {}
57
58// problem: https://leetcode.com/problems/closest-dessert-cost/
59// discuss: https://leetcode.com/problems/closest-dessert-cost/discuss/?currentPage=1&orderBy=most_votes&query=
60
61// submission codes start here
62
63impl Solution {
64    pub fn closest_cost(base_costs: Vec<i32>, topping_costs: Vec<i32>, target: i32) -> i32 {
65        0
66    }
67}
68
69// submission codes end
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn test_1774() {
77    }
78}
79


Back
© 2025 bowen.ge All Rights Reserved.