-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1900-closest-dessert-cost.cpp
More file actions
30 lines (29 loc) · 1.01 KB
/
Copy path1900-closest-dessert-cost.cpp
File metadata and controls
30 lines (29 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts,
int target) {
int closest = INT_MAX;
for (auto c : baseCosts) {
stack<pair<int,int>> states;
states.push({0,c});
while (!states.empty()) {
auto s = states.top();
states.pop();
// check solution
if (s.second == target) return target;
if (abs(s.second-target) < abs(closest-target)) {
closest = s.second;
}
if (abs(s.second-target) == abs(closest-target) && (s.second < closest)) {
closest = s.second;
}
if (s.first == toppingCosts.size()) continue;
// push children
for (int i=0;i<3;i++) {
states.push({s.first+1, s.second + i*toppingCosts[s.first]});
}
}
}
return closest;
}
};