1
+ // Runtime: 12 ms (Top 88.73%) | Memory: 9.9 MB (Top 42.44%)
1
2
class Solution {
2
3
public:
3
-
4
+
4
5
// ans-> store final result
5
6
// mn -> Current minimum difference b/w target and curr_price
6
7
int ans=INT_MAX,mn=INT_MAX;
7
-
8
+
8
9
/*
9
10
i-> index of tc(toppingCosts)
10
11
curr -> current cost taken
11
12
tar -> Target cost
12
- */
13
-
13
+ */
14
+
14
15
void find (int i,vector<int >& tc,int curr, int tar)
15
- {
16
+ {
16
17
/*
17
- if difference b/w current cost and target cost is
18
- less than min difference , so we have to update ans
18
+ if difference b/w current cost and target cost is
19
+ less than min difference , so we have to update ans
19
20
and min difference because we got closest to target
20
21
*/
21
22
if (abs (curr-tar)<mn)
22
- {
23
+ {
23
24
mn=abs (curr-tar);
24
25
ans=curr;
25
26
}
26
-
27
+
27
28
/*
28
- if difference b/w current cost and target cost is
29
- equal to min difference , so we have to update ans
29
+ if difference b/w current cost and target cost is
30
+ equal to min difference , so we have to update ans
30
31
and takin minimum one as condition given in problem
31
32
*/
32
- if (abs (curr-tar)==mn) ans=min (ans,curr);
33
-
33
+ if (abs (curr-tar)==mn) ans=min (ans,curr);
34
+
34
35
/*
35
- If we are going out of bound just return
36
+ If we are going out of bound just return
36
37
because we will nothing get after here
37
38
*/
38
39
if (i>=tc.size () || curr-tar>mn) return ;
39
-
40
-
41
- /* Main interesting thing -> How to recurse */
40
+
41
+ /* Main interesting thing -> How to recurse */
42
42
/*
43
43
Just put all the required conditions
44
-
44
+
45
45
NOTE: We have already taken 1 baseCosts, so left that
46
46
We have to select from tc(toppingCosts)
47
-
47
+
48
48
In our question we have 3 conditon
49
49
1. Take ith toppingCosts and go for next (i+1)th toppingCost
50
50
2. Take ith toppingCosts 2 times and go for next (i+1)th toppingCost
51
51
3. We will not take ith toppingCosts and will select next ones
52
52
*/
53
-
53
+
54
54
// taking ith toppingCosts and moving to (i+1)th toppingCosts
55
- find (i+1 ,tc,curr+tc[i],tar);
56
-
55
+ find (i+1 ,tc,curr+tc[i],tar);
56
+
57
57
// taking ith toppingCosts 2 times and moving to (i+1)th toppingCosts
58
- find (i+1 ,tc,curr+2 *tc[i],tar);
59
-
58
+ find (i+1 ,tc,curr+2 *tc[i],tar);
59
+
60
60
// Without taking ith toppingCosts and move to (i+1)th toppingCosts for next one
61
- find (i+1 ,tc,curr,tar);
62
-
63
-
61
+ find (i+1 ,tc,curr,tar);
62
+
64
63
}
65
64
int closestCost (vector<int >& baseCosts, vector<int >& toppingCosts, int target) {
66
-
65
+
67
66
// take each baseCost every time
68
67
for (auto x:baseCosts)
69
68
{
70
69
// taking ith baseCost and select toppingCosts
71
- find (0 ,toppingCosts,x,target);
70
+ find (0 ,toppingCosts,x,target);
72
71
}
73
-
72
+
74
73
// return closest to target answer
75
74
return ans;
76
-
75
+
77
76
}
78
- };
77
+ };
0 commit comments