Input: [2,3,-1,3] Output: 6 Because, [2,3] are continuous and has the largest product 6.
The steps of the working of the solution is as below:
- Take 2 variables “front_product” and “back_product”.
- front_product will always calculate from front of the array.
- back_product will always calculate from back of the array.
- At every iteration take the max of those values, we get the result
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