Solution to keep a running window between zeros : 98%


  • 0
    T
    
    public class Solution {
        public int maxProduct(int[] nums) {
            int maxProd = Integer.MIN_VALUE;
            int[] runningProd = new int[nums.length];
            int i,j;
            i = 0;
            
            while(i<nums.length)
            {
                //Avoid/Skip all zeros 
                while (i<nums.length && nums[i]==0)
                {
                    runningProd[i] = 0;
                    maxProd = Math.max(runningProd[i],maxProd);
                    i++;
                }
                
                //If we ran out of the array, break
                if (i==nums.length)
                    break;
                
                //else
                //i has first non zero   
                j = i;
                runningProd[i] = nums[i];
                maxProd = Math.max(runningProd[i],maxProd);
                i++;
                //Expand the window while we dont encounter a zero or hit the array end
                while(i<nums.length && nums[i]!=0)
                {
                    runningProd[i] = runningProd[i-1] * nums[i];
                    maxProd = Math.max(runningProd[i],maxProd);
                    i++;
                }
                
                i--;    // i has the digit before the next 0 or either the last digit in the array
                //Start compressing the window from the left
                while(j!=i)
                {
                    maxProd =  Math.max(runningProd[i]/runningProd[j],maxProd);
                    j++;
                }
                
                i+=1;
                
            }
            
            return maxProd;
        }
    }
    '''
    

Log in to reply
 

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