Sunday, 16 May 2021

Maximum Product Subarray

 Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6.


public class MaximumProductSubArray {

    public static void main(String[] args) {

        int[] arr = {-2,1,-4};


        int result = arr[0];

        int max = arr[0];

        int min = arr[0];


        for(int i=1;i<arr.length;i++){

          int  tempMax = Math.max(arr[i], Math.max(max*arr[i],min*arr[i]));

          min = Math.min(arr[i], Math.min(max*arr[i],min*arr[i]));

          max = tempMax;


          result = Math.max(result,max);


        }


        System.out.println(result);


    }

}


Result:8

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐒𝐧 π‹π’π§π€πžπ 𝐋𝐒𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀π₯π₯ 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 π“π«πžπž π“π«πšπ―πžπ«π¬πšπ₯𝐬...