Maximum range length such that A[i] is maximum in given range for all i from [1, N]
Last Updated :
28 Jul, 2021
Given an array arr[] consisting of N distinct integers. For each i (0 ? i < n), find a range [l, r] such that A[i] = max(A[l], A[l+1], …, A[r]) and l ? i ? r and r-l is maximized.
Examples:
Input: arr[] = {1, 3, 2}
Output: {0 0}, {0 2}, {2 2}
Explanation: For i=0, 1 is maximum in range [0, 0] only. For i=1, 3 is maximum in range [0, 2] and for i = 2, 2 is maximum in range [2, 2] only.
Input: arr[] = {1, 2}
Output: {0, 0}, {0, 1}
Naive Approach: The simplest approach to solve the problem is for each i, Iterate in the range [i+1, N-1] using variable r and iterate in the range [i-1, 0] using the variable l and terminate the loop when arr[l] > arr[i] and arr[r]>arr[i] respectively. The answer will be [l, r].
Time Complexity: O(N×N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized further by using a stack data structure. Follow the steps below to solve the problem:
- Initialize two vectors, say left and right that will store the left index and right index for each i respectively.
- Initialize a stack of pairs, say s.
- Insert INT_MAX and -1 as a pair in the stack.
- Iterate in the range [0, N-1] using the variable i and perform the following steps:
- While s.top().first<arr[i], pop the top element from the stack.
- Modify the value of left[i] as s.top().second.
- Push {arr[i], i} in the stack.
- Now remove all the elements from the stack.
- Insert INT_MAX and N in the stack as pairs.
- Iterate in the range [N-1, 0] using the variable i and perform the following steps:
- While s.top().first<arr[i], pop the top element from the stack.
- Modify the value of right[i] as s.top().second.
- Push {arr[i], i} in the stack.
- Iterate in the range [0, N-1] using the variable i and print left[i] +1, right[i] -1 as the answer for ith element.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void MaxRange(vector< int > A, int n)
{
vector< int > left(n), right(n);
stack<pair< int , int > > s;
s.push({ INT_MAX, -1 });
for ( int i = 0; i < n; i++) {
while (s.top().first < A[i])
s.pop();
left[i] = s.top().second;
s.push({ A[i], i });
}
while (!s.empty())
s.pop();
s.push(make_pair(INT_MAX, n));
for ( int i = n - 1; i >= 0; i--) {
while (s.top().first < A[i])
s.pop();
right[i] = s.top().second;
s.push({ A[i], i });
}
for ( int i = 0; i < n; i++) {
cout << left[i] + 1 << ' ' << right[i] - 1 << "\n" ;
}
}
int main()
{
vector< int > arr{ 1, 3, 2 };
int n = arr.size();
MaxRange(arr, n);
return 0;
}
|
Java
import java.awt.*;
import java.util.*;
class GFG{
static class pair<T, V>{
T first;
V second;
}
static void MaxRange(ArrayList<Integer> A, int n)
{
int [] left = new int [n];
int [] right = new int [n];
Stack<pair<Integer,Integer>> s = new Stack<>();
pair<Integer,Integer> x = new pair<>();
x.first =Integer.MAX_VALUE;
x.second = - 1 ;
s.push(x);
for ( int i = 0 ; i < n; i++)
{
while (s.peek().first < A.get(i))
s.pop();
left[i] = s.peek().second;
pair<Integer,Integer> y = new pair<>();
y.first = A.get(i);
y.second = i;
s.push(y);
}
while (!s.empty())
s.pop();
pair<Integer,Integer> k = new pair<>();
k.first =Integer.MAX_VALUE;
k.second = n;
s.push(k);
for ( int i = n - 1 ; i >= 0 ; i--)
{
while (s.peek().first < A.get(i))
s.pop();
right[i] = s.peek().second;
pair<Integer,Integer> y = new pair<>();
y.first = A.get(i);
y.second = i;
s.push(y);
}
for ( int i = 0 ; i < n; i++) {
System.out.print(left[i]+ 1 );
System.out.print( " " );
System.out.println(right[i]- 1 );
}
}
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<>();
arr.add( 1 );
arr.add( 3 );
arr.add( 2 );
int n = arr.size();
MaxRange(arr, n);
}
}
|
Python3
import sys
def MaxRange(A, n):
left = [ 0 ] * n
right = [ 0 ] * n
s = []
s.append((sys.maxsize, - 1 ))
for i in range (n):
while (s[ - 1 ][ 0 ] < A[i]):
s.pop()
left[i] = s[ - 1 ][ 1 ]
s.append((A[i], i))
while ( len (s) ! = 0 ):
s.pop()
s.append((sys.maxsize, n))
for i in range (n - 1 , - 1 , - 1 ):
while (s[ - 1 ][ 0 ] < A[i]):
s.pop()
right[i] = s[ - 1 ][ 1 ]
s.append((A[i], i))
for i in range (n):
print (left[i] + 1 , ' ' , right[i] - 1 )
if __name__ = = "__main__" :
arr = [ 1 , 3 , 2 ]
n = len (arr)
MaxRange(arr, n)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
static void MaxRange(List< int > A, int n)
{
int [] left = new int [n];
int [] right = new int [n];
Stack s = new Stack();
s.Push( new Tuple< int , int >(Int32.MaxValue, -1));
for ( int i = 0; i < n; i++)
{
while (((Tuple< int , int >)s.Peek()).Item1 < A[i])
s.Pop();
left[i] = ((Tuple< int , int >)s.Peek()).Item2;
s.Push( new Tuple< int , int >(A[i], i));
}
while (s.Count > 0)
s.Pop();
s.Push( new Tuple< int , int >(Int32.MaxValue, n));
for ( int i = n - 1; i >= 0; i--) {
while (((Tuple< int , int >)s.Peek()).Item1 < A[i])
s.Pop();
right[i] = ((Tuple< int , int >)s.Peek()).Item2;
s.Push( new Tuple< int , int >(A[i], i));
}
for ( int i = 0; i < n; i++) {
Console.WriteLine((left[i] + 1) + " " + (right[i] - 1));
}
}
static void Main ()
{
List< int > arr = new List< int >();
arr.Add(1);
arr.Add(3);
arr.Add(2);
int n = arr.Count;
MaxRange(arr, n);
}
}
|
Javascript
<script>
function MaxRange(A, n)
{
let left = new Array(n).fill(0),
right = new Array(n).fill(0);
let s = [];
s.push([Number.MAX_SAFE_INTEGER, -1]);
for (let i = 0; i < n; i++)
{
while (s[s.length - 1][0] < A[i])
s.pop();
left[i] = s[s.length - 1][1];
s.push([A[i], i]);
}
while (s.length)
s.pop();
s.push([Number.MAX_SAFE_INTEGER, n]);
for (let i = n - 1; i >= 0; i--)
{
while (s[s.length - 1][0] < A[i])
s.pop();
right[i] = s[s.length - 1][1];
s.push([A[i], i]);
}
for (let i = 0; i < n; i++)
{
document.write(left[i] + 1 + " " )
document.write(right[i] - 1 + "<br>" )
}
}
let arr = [ 1, 3, 2 ];
let n = arr.length;
MaxRange(arr, n);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...