Count of subarrays starting or ending at an index i such that arr[i] is maximum in subarray
Given an array arr[] consisting of N integers, the task is to find the number of subarrays starting or ending at an index i such that arr[i] is the maximum element of the subarray.
Examples:
Input: arr[] = {3, 4, 1, 6, 2}
Output: 1 3 1 5 1
Explanation:
- The subarray starting or ending at index 0 and with maximum arr[0](=3) is {3}. Therefore, the count is 1.
- The subarrays starting or ending at index 1 and with maximum arr[1](=4) are {3, 4}, {4}, and {4, 1}. Therefore, the count is 3.
- The subarray starting or ending at index 2 and with maximum arr[2](=1) is {1}. Therefore, the count is 1.
- The subarrays starting or ending at index 3 and with maximum arr[3](=6) are {3, 4, 1, 6}, {4, 1, 6}, {1, 6}, {6}, and {6, 2}. Therefore, the count is 5.
- The subarray starting or ending at index 4 and with maximum arr[4](=2) is {2}. Therefore, the count is 1.
Input: arr[] = {1, 2, 3}
Output: 1 2 3
Naive Approach: The simplest approach to solve the given problem is for every ith index, iterate backward and forward until the maximum of the subarray remains equal to arr[i] and then print the total count of subarrays obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by storing the index of the next greater element and previous greater element for every index i and find the count of subarrays accordingly for each index. Follow the steps below to solve the given problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int * getPGE( int arr[], int n)
{
int * pge = new int [n];
stack< int > stack;
for ( int i = 0; i < n; i++)
{
while (!stack.empty() &&
arr[stack.top()] <= arr[i])
{
stack.pop();
}
pge[i] = stack.empty() ? -1 : stack.top();
stack.push(i);
}
return pge;
}
int * getNGE( int arr[], int n)
{
int * nge = new int [n];
stack< int > stack;
for ( int i = n - 1; i >= 0; i--)
{
while (!stack.empty() &&
arr[stack.top()] <= arr[i])
{
stack.pop();
}
nge[i] = stack.empty() ? n : stack.top();
stack.push(i);
}
return nge;
}
void countSubarrays( int arr[], int n)
{
int * pge = getPGE(arr, n);
int * nge = getNGE(arr, n);
for ( int i = 0; i < n; i++)
{
cout << nge[i] - pge[i] - 1 << " " ;
}
}
int main()
{
int arr[] = { 3, 4, 1, 6, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
countSubarrays(arr, n);
return 0;
}
|
Java
import java.util.*;
public class GFG {
private static int [] getPGE( int [] arr)
{
int [] pge = new int [arr.length];
Stack<Integer> stack = new Stack<>();
for ( int i = 0 ; i < arr.length; i++) {
while (!stack.isEmpty()
&& arr[stack.peek()] <= arr[i]) {
stack.pop();
}
pge[i] = stack.isEmpty() ? - 1 : stack.peek();
stack.push(i);
}
return pge;
}
private static int [] getNGE( int [] arr)
{
int [] nge = new int [arr.length];
Stack<Integer> stack = new Stack<>();
for ( int i = arr.length - 1 ; i >= 0 ; i--) {
while (!stack.isEmpty()
&& arr[stack.peek()] <= arr[i]) {
stack.pop();
}
nge[i] = stack.isEmpty() ? arr.length
: stack.peek();
stack.push(i);
}
return nge;
}
private static void countSubarrays( int [] arr)
{
int [] pge = getPGE(arr);
int [] nge = getNGE(arr);
for ( int i = 0 ; i < arr.length; i++) {
System.out.print(
nge[i] - pge[i] - 1 + " " );
}
}
public static void main(String[] args)
{
int [] arr = new int [] { 3 , 4 , 1 , 6 , 2 };
countSubarrays(arr);
}
}
|
Python3
pge = []
nge = []
def getPGE(arr, n) :
s = list ()
for i in range ( 0 , n):
while ( len (s) > 0 and arr[s[ - 1 ]] < = arr[i]):
s.pop()
if len (s) = = 0 :
pge.append( - 1 )
else :
pge.append(s[ - 1 ])
s.append(i)
def getNGE(arr, n) :
s = list ()
for i in range (n - 1 , - 1 , - 1 ):
while ( len (s) > 0 and arr[s[ - 1 ]] < = arr[i]):
s.pop()
if len (s) = = 0 :
nge.append(n)
else :
nge.append(s[ - 1 ])
s.append(i)
nge.reverse();
def countSubarrays(arr, n):
getNGE(arr, n);
getPGE(arr, n);
for i in range ( 0 ,n):
print (nge[i] - pge[i] - 1 ,end = " " )
arr = [ 3 , 4 , 1 , 6 , 2 ]
n = len (arr)
countSubarrays(arr,n);
|
C#
using System;
using System.Collections;
class GFG {
static int [] getPGE( int [] arr)
{
int [] pge = new int [arr.Length];
Stack stack = new Stack();
for ( int i = 0; i < arr.Length; i++) {
while (stack.Count > 0 && arr[( int )stack.Peek()] <= arr[i]) {
stack.Pop();
}
pge[i] = stack.Count == 0 ? -1 : ( int )stack.Peek();
stack.Push(i);
}
return pge;
}
static int [] getNGE( int [] arr)
{
int [] nge = new int [arr.Length];
Stack stack = new Stack();
for ( int i = arr.Length - 1; i >= 0; i--) {
while (stack.Count > 0 && arr[( int )stack.Peek()] <= arr[i]) {
stack.Pop();
}
nge[i] = stack.Count == 0 ? arr.Length : ( int )stack.Peek();
stack.Push(i);
}
return nge;
}
static void countSubarrays( int [] arr)
{
int [] pge = getPGE(arr);
int [] nge = getNGE(arr);
for ( int i = 0; i < arr.Length; i++) {
Console.Write((nge[i] - pge[i] - 1) + " " );
}
}
static void Main() {
int [] arr = { 3, 4, 1, 6, 2 };
countSubarrays(arr);
}
}
|
Javascript
<script>
let pge = [];
let nge = [];
function getPGE(arr, n) {
let s = [];
for (let i = 0; i < n; i++)
{
while (s.length > 0 && arr[s[s.length - 1]] <= arr[i])
{
s.pop();
}
if (s.length == 0) pge.push(-1);
else pge.push(s[s.length - 1]);
s.push(i);
}
}
function getNGE(arr, n) {
let s = [];
for (let i = n - 1; i >= 0; i--)
{
while (s.length > 0 && arr[s[s.length - 1]] <= arr[i]) {
s.pop();
}
if (s.length == 0) nge.push(n);
else nge.push(s[s.length - 1]);
s.push(i);
}
nge.reverse();
}
function countSubarrays(arr, n)
{
getNGE(arr, n);
getPGE(arr, n);
for (let i = 0; i < n; i++) {
document.write(nge[i] - pge[i] - 1 + " " );
}
}
let arr = [3, 4, 1, 6, 2];
let n = arr.length;
countSubarrays(arr, n);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
20 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...