Maximum Index

PROBLEM :
Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].

Example :
A : [3 5 4 2]
Output : 2
for the pair (3, 4)

Input:
The first line contains an integer T, depicting total number of test cases.
Then following T lines contains an integer N depicting the size of array and next line followed by the value of array.

Output:
Print the maximum difference of the indexes i and j in a separtate line.

Constraints:
1 = T = 30
1 = N = 1000
0 = A[i] = 100

Example:
Input
1
2
1 10

Output
1

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int Maximum_Index(int [],int ) ;
int main()
 {
int t,no,i ;
int arr[1000] ;
cin>>t ;
while(t--)
{
   cin>>no ;
   for(i=0;i<no;i++)
       cin>>arr[i] ;
   cout<<Maximum_Index(arr,no)<<endl ;
}
return 0;
}

int Maximum_Index(int arr[],int no)
{
    int Lmin[no],Rmax[no] ;
    int i,j,max ;
   
    Lmin[0]=arr[0] ;
    for(i=1;i<no;i++)
        Lmin[i]=arr[i]<Lmin[i-1]?arr[i]:Lmin[i-1] ;
       
    Rmax[no-1]=arr[no-1] ;
    for(j=no-2;j>=0;j--)
        Rmax[j]=arr[j]>Rmax[j+1]?arr[j]:Rmax[j+1] ;
       
    max=0 ;  
    i=0,j=0 ;
    while(i<no&&j<no)
    {
        if(Lmin[i]<Rmax[j])
        {
            max=max>j-i?max:j-i ;
            j++ ;
        }
        else
            i++ ;
    }
    return max ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )