Simple Java solution - a slightly different approach


  • 0
    M
    public class Solution {
        public int integerBreak(int n) {
            /*
                Start dividing by two and then by three, etc.. until the product decreases
                We want to keep all three numbers as close to each other as possible. 
                Product should start decreasing after around 2-4 factors.
            */
            
            int maxProduct = 0;
            int divisor = 2;
            int remainder;
            
            while(true) {
                remainder = n;
                int[] multipliers = new int[divisor];
                for(int i = divisor; i > 0; i--) {
                    multipliers[i - 1] = remainder / i;
                    remainder -= multipliers[i - 1];
                }
                
                int product = 1;
                for(int i = 0; i < divisor; i++) 
                    product *= multipliers[i];
                
                if(product > maxProduct) maxProduct = product;
                else return maxProduct;
                
                divisor++;
            }
        }
    }

Log in to reply
 

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