Simple Java Solution with some explanation


  • 0

    This problem is more straightforward than it seems to be.
    As all the numbers are positive integers in the array, to find out the max result, you just pick the first number and try to get the minimum divisor. How to get the minimum divisor? Get the second number and divide it by all the rest of numbers. Since of that, there are only 3 conditions to discuss.

    1. When there is only 1 number, just return nums[0].
    2. When there are 2 numbers, return nums[0]/nums[1].
    3. When there are more than 2 numbers, return nums[0]/(nums[1]/...../nums[n-1]).
    public String optimalDivision(int[] nums) {
        StringBuffer ret = new StringBuffer();
        if(nums==null||nums.length==0) return new String();
        if(nums.length==1){
            ret.append(nums[0]);
            return ret.toString();
        }
        else if(nums.length==2){
            ret.append(nums[0]);
            ret.append("/");
            ret.append(nums[1]);
            return ret.toString();
        }
        else{
            ret.append(nums[0]);
            ret.append("/");
            ret.append("(");
            for(int i = 1;i<nums.length;i++){
                ret.append(nums[i]);
                ret.append("/");
            }
            ret.setLength(ret.length()-1);
            ret.append(")");
            return ret.toString();
        }
    }

Log in to reply
 

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