343. Integer Break

1. Description

Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

2. Example

Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.

Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

3. Note

  • You may assume that n is not less than 2 and not larger than 58.

4. Solutions

My Accepted Solution

Time complexity: O(n)
Space complexity: O(1)

It is hard to prove, but the result is that if we want to get a max product, we should try to get more 3 numbers.

class Solution 
{
public:
    int integerBreak(int n) 
    {
        unordered_map<int, int> product{{0, 1}, {1, 1}, {2, 1}, {3, 2}, {4, 4}};
        if(n < 5) return product[n];
        
        int threePowers = 1;
        while(n >= 5)
        {
            n -= 3;
            threePowers *= 3;
        }
        
        return n * threePowers;
    }
};
comments powered by Disqus