Skip to content

Commit a4c823e

Browse files
authored
Merge pull request neetcode-gh#2239 from ashutosh2706/add-solution
Create: 0343-integer-break.cpp
2 parents 5064ddf + 827fb16 commit a4c823e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

cpp/0343-integer-break.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.
3+
Return the maximum product that we can get.
4+
5+
Example. For n = 10, we can break it as 10 = 3 + 3 + 4. Product of these integers is 3 x 3 x 4 = 36, which is the maximum product that
6+
we can get in this case. So we return 36 as the answer.
7+
8+
9+
Time: O(n^2)
10+
Space: O(n)
11+
12+
*/
13+
14+
class Solution {
15+
public:
16+
int integerBreak(int n) {
17+
vector<int> dp(n+1, INT_MIN);
18+
dp[0] = 1, dp[1] = 1;
19+
for(int ind=2; ind<=n; ind++) {
20+
for(int i=ind-1; i>=1; i--) {
21+
dp[ind] = max(dp[ind], i * dp[ind - i]);
22+
}
23+
if(ind < n) dp[ind] = max(dp[ind], ind);
24+
}
25+
return dp[n];
26+
}
27+
};
28+

0 commit comments

Comments
 (0)