We want to break the integer n into at least two positive integers such that their product is maximized. For each number i, let dp[i] to be the max production value for breaking the number i. Since dp[i+j] can be i*j,
So, we can try every possible first split j (where 1 ≤ j < i) and take the maximum between splitting further (dp[i-j]) or not splitting (i-j). This way, we build up the solution from smaller numbers.
classSolution {
public:int integerBreak(int n) {
if (n ==2) return1;
if (n ==3) return2;
if (n ==4) return4;
int result =1;
if (n %3==0) {
int m = n /3;
for (int i =0; i < m; ++i) result *=3;
} elseif (n %3==2) {
int m = n /3;
for (int i =0; i < m; ++i) result *=3;
result *=2;
} elseif (n %3==1) {
int m = (n -4) /3;
for (int i =0; i < m; ++i) result *=3;
result *=4;
}
return result;
}
};
classSolution {
publicintintegerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
if (n == 4) return 4;
int result = 1;
if (n % 3 == 0) {
int m = n / 3;
result = (int) Math.pow(3, m);
} elseif (n % 3 == 2) {
int m = n / 3;
result = (int) Math.pow(3, m) * 2;
} elseif (n % 3 == 1) {
int m = (n - 4) / 3;
result = (int) Math.pow(3, m) * 4;
}
return result;
}
}
classSolution {
funintegerBreak(n: Int): Int {
if (n ==2) return1if (n ==3) return2if (n ==4) return4var result = 1if (n % 3==0) {
val m = n / 3 repeat(m) { result *=3 }
} elseif (n % 3==2) {
val m = n / 3 repeat(m) { result *=3 }
result *=2 } elseif (n % 3==1) {
val m = (n - 4) / 3 repeat(m) { result *=3 }
result *=4 }
return result
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defintegerBreak(self, n: int) -> int:
if n ==2:
return1if n ==3:
return2if n ==4:
return4 result =1if n %3==0:
m = n //3 result =3** m
elif n %3==2:
m = n //3 result = (3** m) *2elif n %3==1:
m = (n -4) //3 result = (3** m) *4return result
impl Solution {
pubfninteger_break(n: i32) -> i32 {
if n ==2 { return1; }
if n ==3 { return2; }
if n ==4 { return4; }
letmut result =1;
if n %3==0 {
let m = n /3;
for _ in0..m {
result *=3;
}
} elseif n %3==2 {
let m = n /3;
for _ in0..m {
result *=3;
}
result *=2;
} elseif n %3==1 {
let m = (n -4) /3;
for _ in0..m {
result *=3;
}
result *=4;
}
result
}
}