
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Product Subarray with Negative Product Case in C++
In this problem, we are given an array of integers(positive as well as negative). Our task is to create a program to calculate the Maximum Product Subarray in C++.
Problem Solution − Here, we have an array that contains positive, negative, and zero numbers. We need to find the product of subarrays created by elements of the array. And maximize the product of the subarray.
Let’s take an example to understand the problem,
Input
arr[] = {-1, 2, -7, -5, 12, 6}
Output
5040
Explanation
The subarray with the maximum product is {2, -7, -5, 12, 6}
Product = 5040
Solution Approach
To solve this problem, we are given an array and the maximum product of the subarray and manage maxVal which is the maximum product upto the current element and minVal is the negative maxima of the product. Then based on the current value, the maxVal and minVal are updated as −
Case 1 - Element is positive − Update maxVal and minVal by multiplying the array.
Case 2 - Element is Zero − Break the current subarray as multiplying by 0 will result in 0.
Case 3 - Element is negative − Update Both values with negative values making its maxima.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int min(int a, int b){ if(a < b) return a; return b; } int max(int a, int b){ if(a > b) return a; return b; } int CalcMaxProductSubArray(int arr[], int n) { int i = 0; int maxVal = -1000; int localMax = 1; int localMin = 1; int lastMax; while(i < n) { int currentVal = arr[i]; if (currentVal > 0) { localMax = (localMax * currentVal); localMin = min(1, localMin * currentVal); } else if (currentVal < 0) { lastMax = localMax; localMax = (localMin * currentVal); localMin = (lastMax * currentVal); } else { localMin = 1; localMax = 0; } maxVal = max(maxVal, localMax); if (localMax <= 0) localMax = 1; i++; } return maxVal; } int main(){ int arr[] = { -1, 2, -7, -5, 12, 6 }; int n = 6; cout<<"The maximum product Subarray is "<<CalcMaxProductSubArray(arr, n); return 0; }
Output
The maximum product Subarray is 5040