-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosestCost.cpp
More file actions
33 lines (27 loc) · 950 Bytes
/
closestCost.cpp
File metadata and controls
33 lines (27 loc) · 950 Bytes
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
31
32
33
class Solution {
public:
int ans = 100000, diff = 100000, t;
void helper(vector<int>& toppingCosts, int currSum, int index) {
int currDiff = abs(t - currSum);
if (diff < currSum - t) {
return;
} else if (diff >= currDiff) {
if (diff > currDiff) {
ans = currSum;
diff = currDiff;
} else {
ans = min(ans, currSum);
}
}
if(index == toppingCosts.size()) return;
helper(toppingCosts, currSum, index + 1);
helper(toppingCosts, currSum + toppingCosts[index], index + 1);
helper(toppingCosts, currSum + 2 * toppingCosts[index], index + 1);
}
int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts, int target) {
t = target;
for (int base: baseCosts)
helper(toppingCosts, base, 0);
return ans;
}
};