-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCOINS.cpp
56 lines (54 loc) · 1.11 KB
/
COINS.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<iostream>
#include<map>
#define ll long long int
using namespace std;
map<ll,ll> coins;
map<ll,ll>::iterator x;
ll maxsum(ll n)
{
ll s1,s2,s3,sum;
if(n<(n/2+n/3+n/4)) //checks whether for a given n it is less than n/2+n/3+n/4 (this will satisfy for n>3)
{
x=coins.find(n/2); //finds for n/2 in map
if(x==coins.end()) //in case n/2 is not found find() will return end()
{
s1=maxsum(n/2); //that means we need to go top to bottom and find the sum for lower sub values
}
else
{
s1=x->second; //if found then return that value of sum from the map
}
x=coins.find(n/3); //same as for n/2
if(x==coins.end())
{
s2=maxsum(n/3);
}
else
{
s2=x->second;
}
x=coins.find(n/4);
if(x==coins.end())
{
s3=maxsum(n/4); //same as for n/4
}
else
{
s3=x->second;
}
sum=s1+s2+s3; //after recursive calling till bottom store the sum corresponding to n in map
coins.insert(pair<ll,ll>(n,sum));
return sum;
}
else
return n; //for n<=3
}
int main()
{
ll c;
while(scanf("%lld",&c)!=EOF)
{
printf("%lld\n",maxsum(c));
}
return 0;
}