10. Maximum Product Subarray

Topic :

arrays

Difficulty :

medium

Problem Link :


problem statement

Given an integer array nums, find a subarray that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

Example 1:

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
 

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -10 <= nums[i] <= 10
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

solution

import java.io.*;
import java.util.*;
 class Maximum_Product_Subarray
{
  public static void main(String  args[]){
    int nums[]={2,3,-2,4};
    System.out.println(maxProduct(nums));
   }
  static int maxProduct(int[] nums) {
     int n=nums.length;   
     int ans=nums[0]; // store the first element as ans
     int max=ans; // store first ele as max
     int min=ans;// store the first element as min
     // because if the array conatined only 1 element then ans,max,min all equal to nums[0]   
       for(int i=1;i<n;i++){
            if(nums[i]<0) // if ele is -ve 
            { // swap the max and min
                int temp=max;
                max=min;
                min=temp;
            }
            
            max=Math.max(nums[i],nums[i]*max);
            min=Math.min(nums[i],nums[i]*min);
            
            ans=Math.max(ans,max);
        }
        
        return ans;
    } 
}
Copyright © 2023 KIZLE. - All Rights Reserved.
Website by Kounik Maitra