Max product subaaray


  • 0
    S
    class Solution {
        public int maxProduct(int[] nums) {
            int max = nums[0];
            int temp_min = nums[0];
            int temp_max = nums[0];
            int runningVal = nums[0];
            for(int i=1; i<nums.length; i++){
             // swap
               if(nums[i] < 0){
                 int temp = temp_min;
                 temp_min = temp_max;
                 temp_max = temp;
               } else if(nums[i]==0){ //reset
                    temp_min = 0;
                    temp_max = 0;
               }
               temp_min = Math.min(nums[i], nums[i]*temp_min);
               temp_max = Math.max(nums[i], nums[i]*temp_max);
                
                max = Math.max(max, temp_max);
            }
            return max;
        }
    }
    

Log in to reply
 

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