AdSense

Sunday, May 29, 2016

Integer Break

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.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

if n <= 1, equally divid the number by 2.
else
   if n % 3 == 0, return the product of all 3s.
   else if n % 3 == 1, return product of (n / 3 - 1) of 3s and two 2s.
   else, return the product of all 3s and one 2.


public int integerBreak(int n) {
        if (n / 3 <= 1) 
            return (n / 2) * (n - n / 2);
        if (n % 3 == 0)
            return (int)Math.pow(3, n / 3);
        else if (n % 3 == 1) {
            int p = n / 3;
            int remd = n - (p - 1) * 3;
            return remd * (int)Math.pow(3, p - 1);
        } else 
            return (int)Math.pow(3, n / 3) * 2;
    }