Integer Break
Medium dynamic-programming · math
Description
Constraints
2 <= n <= 58
Examples
Input: n = 10
Output: 36
3 * 3 * 4
Hints (1)
- Favour factors of 3; for small n handle 2 and 3 specially.
Solutions
Greedy factors of three. · Time O(n) · Space O(1)
func integerBreak(n int) int {
if n <= 3 {
return n - 1
}
product := 1
for n > 4 {
product *= 3
n -= 3
}
return product * n
}
Greedy factors of three. · Time O(n) · Space O(1)
function integerBreak(n) {
if (n <= 3) return n - 1;
let product = 1;
while (n > 4) { product *= 3; n -= 3; }
return product * n;
}
Greedy factors of three. · Time O(n) · Space O(1)
function integerBreak($n) {
if ($n <= 3) { return $n - 1; }
$product = 1;
while ($n > 4) { $product *= 3; $n -= 3; }
return $product * $n;
}
Greedy factors of three. · Time O(n) · Space O(1)
def integerBreak(n):
if n <= 3:
return n - 1
product = 1
while n > 4:
product *= 3
n -= 3
return product * n
Greedy factors of three. · Time O(n) · Space O(1)
function integerBreak(n: number): number {
if (n <= 3) return n - 1;
let product = 1;
while (n > 4) { product *= 3; n -= 3; }
return product * n;
}
Create a free account to submit solutions, track progress and save problems.
Create account