VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-product-of-indexes-of-next-greater-on-left-and-right/

⇱ Maximum product of indexes of next greater on left and right - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum product of indexes of next greater on left and right

Last Updated : 11 Jul, 2025

Given an array arr[1..n], for each element at position i (1 <= i <= n), define the following:

  • left(i) is the closest index j such that j < i and arr[j] > arr[i]. If no such j exists, then left(i) = 0.
  • right(i) is the closest index k such that k > i and arr[k] > arr[i]. If no such k exists, then right(i) = 0.
  • LRproduct(i) = left(i) * right(i).

The task is to find the maximum LR product of the given array.

Examples:

Input: arr[] = [1, 1, 1, 1, 0, 1, 1, 1, 1, 1]
Output: 24
Explanation: All elements are equal except 0. Only for 0, greater elements exist. On the left half, the closest greater element is at index 4 and on the right half, it is at index 6. The maximum product is 4 × 6 = 24.

Input: arr[] = [5, 4, 3, 4, 5]
Output: 8
Explanation: For [5, 4, 3, 4, 5]: left[] = [0, 1, 2, 1, 0], right[] = [0, 5, 4, 5, 0]
LRproduct[] = [0, 5, 8, 5, 0]. The maximum value in LRproduct is 8.

Please note indexes are considered from 1 to n and 0 is used for filling in cases when left(i) and/or right(i) do not exist.

Using Monotonic Stack With 2 Arrays - O(n) Time and O(n) Space

The idea is to find the closest greater elements on both left and right for each element. Using a monotonic stack, we efficiently compute left(i) and right(i) in linear time. The key observation is that elements are processed in increasing order, ensuring each element is pushed and popped at most once. Finally, we compute LRproduct for all indices and return the maximum value.


Output
24

Using a Single Array - O(n) Time and O(n) Space

The idea is to find the next greater element to left, we used a stack from the left, and the same stack is used for multiplying the right greatest element index with the left greatest element index.


Output
24


We can further optimize this using a single for loop. Please refer Largest Area in a Histogram and try to solve this problem using single stack and single loop,


Comment
Article Tags:
Article Tags: