Maximum Product Sub array [ Microsoft – Amazon ]

Problem : Given an array that contains both positive and negative integers, find the product of the maximum product subarray.

Link

Discussion: It is a Similiar problem to maximum sum sub array problem.
Notice,maximum product can also be obtained by minimum (negative) product ending with the last element multiplied by this element.
we use mn_end_here(can be either a negative value or 1) and mx_end_here(can be either a positive value or 1)
So when we find a positive value we update the mx_end_here(multiply).
when we find a negative value mx_end_here will be either 1(as it cant be a negative value)
or multiplied value of mn_end_here with the new negative value.
and mn_end_here will be mx_end_here multiplied by new value(positive value multiplied by negative value will become a negative value.)

#include <stdio.h>

int main() {
	//code
	int arr[15];
	int mx_end_here,mn_end_here;
	int mx_so_far;
	int t,i,n,tmp;
	scanf("%d",&t);
	while(t--)
	{
	    scanf("%d",&n);
	    mx_so_far=1;
	    mx_end_here=1;
	    mn_end_here=1;
	    for(i=0;i<n;i++)
	    {
	        scanf("%d",&arr[i]);
	        if(arr[i]==0)
	        {
	            mn_end_here=1;
	            mx_end_here=1;
	        }
	        else if(arr[i]>0)
	        {
	            mx_end_here=(mx_end_here*arr[i]>1?mx_end_here*arr[i]:1);
	            mn_end_here=(mn_end_here*arr[i]<0?mn_end_here*arr[i]:1);
	        }
	        else if(arr[i]<0)
	        {
	            tmp=mx_end_here;
	            mx_end_here=(mn_end_here*arr[i]>0?mn_end_here*arr[i]:1);
	            mn_end_here=tmp*arr[i];
	        }
	        if(mx_so_far<mx_end_here)
	        mx_so_far=mx_end_here;
	    }
	    printf("%d\n",mx_so_far);
	}
	return 0;
}

 

Comments are closed.