Given an integer array, find the maximum product made from continuous elements in that array. Solution in C++

Example 1:

Input: [2,3,-1,3]
Output: 6
Explanation: [2,3] are continuous and has the largest product 6.

The steps of the working of the solution is as below:

1. Take 2 variables “front_product” and “back_product”.
2. front_product will always calculate from front of the array.
3. back_product will always calculate from back of the array.
4. At every iteration take the max of those values, we get the result.

Time : O(n)
Space : O(1)

Solution in C++



#include<iostream>
#include<vector>

using namespace std;


int max_product(int A[], int n) 
{
	int front_product = 1;
	int back_product = 1;
	int ans = INT_MIN;
	for (int i = 0; i < n; ++i) 
	{
		front_product *= A[i];
		back_product *= A[n - i - 1];

		ans = max(ans,max(front_product,back_product));

		// if the value is 0, then assign 1 to it.
		front_product = front_product == 0 ? 1 : front_product;
		back_product = back_product == 0 ? 1 : back_product;
	}
	return ans;
}

int main()
{
	int array[] = {2, 3, -2, 4};
	int result = max_product(array, 4);
	cout<<"The maximum product of sub array is = "<<result<<endl;
}

Output:

The maximum product of continuous sub array is = 6

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *