forked from Astha369/CPP_Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntegerBreak.cpp
43 lines (36 loc) · 833 Bytes
/
IntegerBreak.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
/* LeetCode Problem 343. Integer Break
Given an integer n, break it into the sum of k positive integers, where k >= 2,
and maximize the product of those integers.
Return the maximum product you can get.
Example 1:
Input: n = 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: n = 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Constraints:
2 <= n <= 58
*/
class Solution {
public:
int integerBreak(int n) {
int ans = 1;
if(n>=5) {
while(n>0) {
if(n>=3 && n!=4) {
ans *= 3;
n = n-3;
} else {
ans *= n;
n=0;
}
}
} else {
ans *= (n/2);
ans *= (n - (n/2));
}
return ans;
}
};