
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 Using Two Traversals in C++
In this problem, we are given an array arr[] of integers. Our task is to create a program to find the Maximum Product Subarray - Using Two Traversals in C++.
Problem description − Here in the array, we will find the maximum product subarray using two traversals one from index 0 and another index (n-1).
Let’s take an example to understand the problem,
Input
arr[] = {4, -2, 5, -6, 0, 8}
Output
240
Example
Subarray = {4, -2, 5, -6} Maximum product = 4 * (-2) * 5 * (-6) = 240
Solution Approach
To solve this problem using two traversals. Here, we will find the maximum product using two local maximum values for traversal from left to right i.e. from index 0 to n-1. And one for traversal from right to left i.e. from index n-1 to 0. The rest algorithm is the same as finding the maximum product subarray.
Program to illustrate the working of our solution,
Example
#include<iostream> using namespace std; int CalcMaxProductSubArray(int arr[], int n) { int frntMax = 1, rearMax = 1, maxVal = 1; for (int i=0; i<n; i++) { frntMax = frntMax*arr[i]; if (frntMax == 0) frntMax = 1; } for (int i=n-1; i>=0; i--) { rearMax = rearMax * arr[i]; if (rearMax == 0) rearMax = 1; } maxVal = max(frntMax, rearMax); return maxVal; } int main() { int arr[] = {4, -2, 5, -6, 0, 8}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"Maximum product subarray is "<<CalcMaxProductSubArray(arr, n); return 0; }
Output
Maximum product subarray is 240
Advertisements