Program to find maximum product subarray in C
Method 1: brust force
#include <stdio.h>
void main() {
int a[5]={-1,2,3,4,-6};
int n=5;
int i,j,k;
int product;
int max=0;
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
product=1;
for(k=i;k<j;k++)
{
product*=a[k];
if(product>max)
{
max=product;
}
}
}
}
printf("%d",max);
}
But the complexity to find maximum product subarray is O(n^3) because three for loop is used in the program.
Method 2: optimal solution to find maximum product subarray.
#include <stdio.h>
void main() {
int a[5]={-1,2,3,4,-6};
int n=5;
int i;
int pre=1;
int suff=1;
int ans=0;
for(i=0;i<n;i++)
{
if(pre==0)
pre=1;
if(suff==0)
suff=1;
pre=pre*a[i];
suff=suff*a[n-i-1];
if(pre>=suff&&pre>ans)
ans=pre;
if(suff>pre&&suff>ans)
ans=suff;
}
printf("%d",ans);
}
In optimal solution to find product of subarray
Complexity is O(n) which is less than brust force method.
0 Comments