
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 of Indexes of Next Greater on Left and Right in C++
In this tutorial, we will be discussing a program to find maximum product of indexes of next greater on left and right.
For this we will be provided with an array of integers. Our task is to find the element with maximum Left-Right product (L(i)*R(i) where L(i) is closest index on left side and greater than current element and R(i) is closest index on right side and greater than current element).
Example
#include <bits/stdc++.h> using namespace std; #define MAX 1000 //finding greater element on left side vector<int> nextGreaterInLeft(int a[], int n) { vector<int> left_index(MAX, 0); stack<int> s; for (int i = n - 1; i >= 0; i--) { while (!s.empty() && a[i] > a[s.top() - 1]) { int r = s.top(); s.pop(); left_index[r - 1] = i + 1; } s.push(i + 1); } return left_index; } //finding greater element on right side vector<int> nextGreaterInRight(int a[], int n) { vector<int> right_index(MAX, 0); stack<int> s; for (int i = 0; i < n; ++i) { while (!s.empty() && a[i] > a[s.top() - 1]) { int r = s.top(); s.pop(); right_index[r - 1] = i + 1; } s.push(i + 1); } return right_index; } //finding maximum LR product int LRProduct(int arr[], int n) { vector<int> left = nextGreaterInLeft(arr, n); vector<int> right = nextGreaterInRight(arr, n); int ans = -1; for (int i = 1; i <= n; i++) { ans = max(ans, left[i] * right[i]); } return ans; } int main() { int arr[] = { 5, 4, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[1]); cout << LRProduct(arr, n); return 0; }
Output
8
Advertisements