Easy-understand Java solution


  • 0
    C
    public class Solution {
    
        public int integerBreak(int n) {
            return intb(n, true);
        }
    
        public int intb(int n, boolean firsttime) {
            if (firsttime) {
                if (n < 4) {
                    return n - 1;
                } else {
                    return intb(n, false);
                }
            } else {
                if (n < 4) {
                    return n;
                } else {
                    return Math.max(2 * intb(n - 2, false), 3 * intb(n - 3, false));
                }
            }
        }
    }

  • 0
    B
    public int integerBreak(int n) {
        //  O(log(n)) time and O(1) space solution
        if(n == 2) return 1;
        if(n == 3) return 2;
        int mod = n % 3;
        int div = n / 3;
        if (mod == 0) {
            return pow(3, div);
        } else if (mod == 1) {
            return pow(3, div - 1) * 4;
        } else {
            return pow(3, div) * 2;
        }
    

    }

    static int pow(int x, int n) {
        int result = 1;
        while (n > 0) {
            int mod = n % 2;
            if (mod == 1) {
                result *= x;
            }
    
            n = n / 2;
            x *= x;
        }
    
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.