Was it helpful?

Question


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

 Live Demo

#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
raja
Published on 09-Sep-2020 13:03:39

Was it helpful?
Not affiliated with Tutorialspoint
scroll top