DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Edited on

Maximum product subarray

Problem

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

Using prefix and suffix array

class Solution {
    public int maxProduct(int[] nums) {

        int prefix[]  = new int[nums.length];
        int suffix[] = new int[nums.length];
        for(int i=0;i<nums.length;i++){
            prefix[i] = nums[i];
            suffix[i] = nums[i];
        }
        for(int i=1;i<nums.length;i++){
            int val = prefix[i]*prefix[i-1];
            prefix[i] = val ==0 ? prefix[i] : val; // imp
        }
        int max = Integer.MIN_VALUE;

        for(int i=0;i<nums.length;i++){
            max = Math.max(max, nums[i]);
        }
        for(int i = nums.length-2;i>=0;i--){
            int val = suffix[i]*suffix[i+1];
            suffix[i] = val ==0 ? suffix[i] : val;// imp

        }
        for(int i=0;i<nums.length;i++){
            int current = Math.max(prefix[i],suffix[i]);
            max = Math.max(max, current);
        }
        return max;
    }
}
Enter fullscreen mode Exit fullscreen mode

More concise and memory efficient

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)