DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Maximum product subarray

Problem

TC: O(n)O(n)
SC: O(n)O(n)

class Solution {
    public int maxProduct(int[] nums) {
        // note: prefix and suffix variables are keeping track if history
        int prefix  = 1;
        int suffix = 1;
        int max = Integer.MIN_VALUE;
        for(int i =0;i<nums.length;i++){
            if(prefix ==0) prefix = 1;
            if(suffix ==0) suffix = 1;
            prefix*=nums[i];
            suffix*=nums[nums.length-i-1];
            max = Integer.max(max, Integer.max(prefix, suffix));
        }
        return max;
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)