5 line Java Solution beats 92%


  • 0
    V

    public class Solution {
    public int maxProduct(int[] nums) {
    int res=Integer.MIN_VALUE,fw=1,bw=1,n=nums.length;

       for(int i=0;i<n;i++) {
            fw*=nums[i];
            bw*=nums[n-1-i];
            res=Math.max(res,Math.max(fw,bw));
            if(fw==0)fw=1;
            if(bw==0)bw=1;
       }
       
       return res;
       
    }
    

    }
    Just calculate products from the start and end and when you hit a zero reset the product to 1, select the max values between the products.


Log in to reply
 

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