Maximize product of a strictly increasing or decreasing subarray | Java program to implement the above approach ; Function to find the maximum product of subarray in the array , arr [ ] ; Maximum positive product ending at the i - th index ; Minimum negative product ending at the current index ; Maximum product up to i - th index ; Check if an array element is positive or not ; Traverse the array ; If current element is positive ; Update max_ending_here ; Update min_ending_here ; Update flag ; If current element is 0 , reset the start index of subarray ; Update max_ending_here ; Update min_ending_here ; If current element is negative ; Stores max_ending_here ; Update max_ending_here ; Update min_ending_here ; Update max_so_far , if needed ; If no array elements is positive and max_so_far is 0 ; Function to find the maximum product of either increasing subarray or the decreasing subarray ; Stores start index of either increasing subarray or the decreasing subarray ; Initially assume maxProd to be 1 ; Traverse the array ; Store the longest either increasing subarray or the decreasing subarray whose start index is i ; Check for increasing subarray ; Insert elements of increasing subarray ; Check for decreasing subarray ; Insert elements of decreasing subarray ; Stores maximum subarray product of current increasing or decreasing subarray ; Update maxProd ; Update i ; Finally print maxProd ; Driver Code
import java . util . * ; class GFG { static int maxSubarrayProduct ( Vector < Integer > arr , int n ) { int max_ending_here = 1 ; int min_ending_here = 1 ; int max_so_far = 0 ; int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr . get ( i ) > 0 ) { max_ending_here = max_ending_here * arr . get ( i ) ; min_ending_here = Math . min ( min_ending_here * arr . get ( i ) , 1 ) ; flag = 1 ; } else if ( arr . get ( i ) == 0 ) { max_ending_here = 1 ; min_ending_here = 1 ; } else { int temp = max_ending_here ; max_ending_here = Math . max ( min_ending_here * arr . get ( i ) , 1 ) ; min_ending_here = temp * arr . get ( i ) ; } if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; } if ( flag == 0 && max_so_far == 0 ) return 0 ; return max_so_far ; } static int findMaxProduct ( int [ ] a , int n ) { int i = 0 ; int maxProd = 1 ; while ( i < n ) { Vector < Integer > v = new Vector < > ( ) ; v . add ( a [ i ] ) ; if ( i < n - 1 && a [ i ] < a [ i + 1 ] ) { while ( i < n - 1 && a [ i ] < a [ i + 1 ] ) { v . add ( a [ i + 1 ] ) ; i += 1 ; } } else if ( i < n - 1 && a [ i ] > a [ i + 1 ] ) { while ( i < n - 1 && a [ i ] > a [ i + 1 ] ) { v . add ( a [ i + 1 ] ) ; i += 1 ; } } int prod = maxSubarrayProduct ( v , v . size ( ) ) ; maxProd = Math . max ( maxProd , prod ) ; i ++ ; } return maxProd ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 10 , 8 , 1 , 100 , 101 } ; int N = arr . length ; System . out . print ( findMaxProduct ( arr , N ) ) ; } }