Maximum Distance

You have been given an array 'A' of N integers. You need to find the maximum value of j - i subjected to the constraint of A[i] <= A[j], where ‘i’ and ‘j’ are the indices of the array.

For example :
If 'A' = {3, 5, 4, 1}

then the output will be 2.
Maximum value occurs for the pair (3, 4)
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases are as follows.

The first line of each test case contains an integer ‘N’ which denotes the size of the array.

The second line of each test case contains elements of the array. The line consists of values of elements of the array separated by a single space.
Output Format:
For each test case, print a single line containing a single integer denoting the maximum value of j - i subjected to the condition A[i] <= A[j].

The output of each test case will be printed in a separate line.

Note:

You don’t have to print anything; it has already been taken care of. Just implement the given function. 
Constraints:
1 <= T <= 100
1 <= N <= 10 ^ 4
-10 ^ 5 <= A[i] <= 10 ^ 5

Time limit: 1 sec.
Follow Up:
Can you solve it using O(N) time complexity?
CodingNinjas
author
2y
Efficient approach

The idea behind this approach is to create a monotonously decreasing array and comparing its values with the given array to find the maximum distance.

  • Create an auxiliary array ‘RMax’...read more
Help your peers!
Add answer anonymously...
MakeMyTrip Full Stack Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter