DevPath

← All problems

Integer Break

Medium dynamic-programming · math

Description

Break n into at least two positive integers and return the maximum product of those parts.

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
}

Create a free account to submit solutions, track progress and save problems.

Create account