-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
36 lines (29 loc) · 771 Bytes
/
Copy pathsolution.cpp
File metadata and controls
36 lines (29 loc) · 771 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
34
35
36
class Solution
{
public:
// HashMap to store already computed answers
unordered_map<int, int> dp;
int solve(int n)
{
// Base case:
// For 0 or 1, breaking is useless
if (n <= 1)
return n;
// If already calculated, return stored answer
if (dp.count(n))
return dp[n];
// Recursively calculate the broken sum
int broken =
solve(n / 2) +
solve(n / 3) +
solve(n / 4);
// Store the maximum between:
// original number OR broken recursive sum
return dp[n] = max(n, broken);
}
int maxSum(int n)
{
// Start recursive calculation
return solve(n);
}
};