📌  相关文章
📜  给定一个数组 arr[],找到最大值 j - i 使得 arr[j] > arr[i]

📅  最后修改于: 2022-05-13 01:57:47.667000             🧑  作者: Mango

给定一个数组 arr[],找到最大值 j - i 使得 arr[j] > arr[i]

给定一个数组 arr[],找到最大值 j - i 使得 arr[j] > arr[i]。

例子 :

Input: {34, 8, 10, 3, 2, 80, 30, 33, 1}
  Output: 6  (j = 7, i = 1)

  Input: {9, 2, 3, 4, 5, 6, 7, 8, 18, 0}
  Output: 8 ( j = 8, i = 0)

  Input:  {1, 2, 3, 4, 5, 6}
  Output: 5  (j = 5, i = 0)

  Input:  {6, 5, 4, 3, 2, 1}
  Output: -1 

方法一(简单但低效)
运行两个循环。在外循环中,从左侧一个一个地选择元素。在内部循环中,将选取的元素与从右侧开始的元素进行比较。当你看到一个大于选取元素的元素时停止内部循环并继续更新迄今为止的最大 ji。

C++
// CPP program for the above approach
#include 
using namespace std;
 
/* For a given array arr[],
   returns the maximum j – i such
   that arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff = -1;
    int i, j;
 
    for (i = 0; i < n; ++i) {
        for (j = n - 1; j > i; --j) {
            if (arr[j] > arr[i] && maxDiff < (j - i))
                maxDiff = j - i;
        }
    }
 
    return maxDiff;
}
 
int main()
{
    int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    cout << "\n" << maxDiff;
    return 0;
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


C
// C program for the above approach
#include 
/* For a given array arr[],
   returns the maximum j – i such
   that arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff = -1;
    int i, j;
 
    for (i = 0; i < n; ++i) {
        for (j = n - 1; j > i; --j) {
            if (arr[j] > arr[i] && maxDiff < (j - i))
                maxDiff = j - i;
        }
    }
 
    return maxDiff;
}
 
int main()
{
    int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    printf("\n %d", maxDiff);
    getchar();
    return 0;
}


Java
// Java program for the above approach
class FindMaximum {
    /* For a given array arr[],
        returns the maximum j-i such
       that arr[j] > arr[i] */
    int maxIndexDiff(int arr[], int n)
    {
        int maxDiff = -1;
        int i, j;
 
        for (i = 0; i < n; ++i) {
            for (j = n - 1; j > i; --j) {
                if (arr[j] > arr[i] && maxDiff < (j - i))
                    maxDiff = j - i;
            }
        }
 
        return maxDiff;
    }
 
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        FindMaximum max = new FindMaximum();
        int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.length;
        int maxDiff = max.maxIndexDiff(arr, n);
        System.out.println(maxDiff);
    }
}


Python3
# Python3 program to find the maximum
# j – i such that arr[j] > arr[i]
 
# For a given array arr[], returns
# the maximum j – i such that
# arr[j] > arr[i]
 
 
def maxIndexDiff(arr, n):
    maxDiff = -1
    for i in range(0, n):
        j = n - 1
        while(j > i):
            if arr[j] > arr[i] and maxDiff < (j - i):
                maxDiff = j - i
            j -= 1
 
    return maxDiff
 
 
# driver code
arr = [9, 2, 3, 4, 5, 6, 7, 8, 18, 0]
n = len(arr)
maxDiff = maxIndexDiff(arr, n)
print(maxDiff)
 
# This article is contributed by Smitha Dinesh Semwal


C#
// C# program to find the maximum
// j – i such that arr[j] > arr[i]
using System;
class GFG {
    // For a given array arr[], returns
    // the maximum j-i such that arr[j] > arr[i]
    static int maxIndexDiff(int[] arr, int n)
    {
        int maxDiff = -1;
        int i, j;
 
        for (i = 0; i < n; ++i) {
            for (j = n - 1; j > i; --j) {
                if (arr[j] > arr[i] && maxDiff < (j - i))
                    maxDiff = j - i;
            }
        }
 
        return maxDiff;
    }
 
    // Driver program
    public static void Main()
    {
 
        int[] arr = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.Length;
        int maxDiff = maxIndexDiff(arr, n);
        Console.Write(maxDiff);
    }
}
// This Code is Contributed by Sam007


PHP
 arr[i]
 
// For a given array arr[], returns
// the maximum j – i such that
// arr[j] > arr[i]
function maxIndexDiff($arr, $n)
{
    $maxDiff = -1;
     
    for ($i = 0; $i < $n; ++$i)
    {
        for ($j = $n - 1; $j > $i; --$j)
        {
            if($arr[$j] > $arr[$i] &&
               $maxDiff < ($j - $i))
                $maxDiff = $j - $i;
        }
    }
 
    return $maxDiff;
}
 
// Driver Code
$arr = array(9, 2, 3, 4, 5,
             6, 7, 8, 18, 0);
$n = count($arr);
$maxDiff = maxIndexDiff($arr, $n);
echo $maxDiff ;
 
// This code is contributed by Sam007
?>


Javascript


C++
/* For a given array arr[],
   calculates the maximum j – i
   such that arr[j] > arr[i] */
#include 
using namespace std;
 
int main()
{
    vector v{
        34, 8, 10, 3, 2, 80, 30, 33, 1
    };
    int n = v.size();
    vector maxFromEnd(n + 1, INT_MIN);
 
    // create an array maxfromEnd
    for (int i = v.size() - 1; i >= 0; i--) {
        maxFromEnd[i] = max(maxFromEnd[i + 1], v[i]);
    }
 
    int result = 0;
 
    for (int i = 0; i < v.size(); i++) {
        int low = i + 1, high = v.size() - 1, ans = i;
 
        while (low <= high) {
            int mid = (low + high) / 2;
 
            if (v[i] <= maxFromEnd[mid]) {
               
                // We store this as current answer and look
                // for further larger number to the right
                // side
                ans = max(ans, mid);
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
        // keeping a track of the
        // maximum difference in indices
        result = max(result, ans - i);
    }
    cout << result << endl;
}


C
/* C program to implement
the above approach */
 
/* For a given array arr[],
calculates the maximum j – i
such that arr[j] > arr[i] */
#include 
#include 
 
/* Function for maximum of
two numbers in C */
int max(int num1, int num2)
{
    return (num1 > num2 ) ? num1 : num2;
}
 
int main()
{
    int v[] = { 34, 8, 10, 3, 2, 80, 30, 33, 1 };
    int n = sizeof(v) / sizeof(v[0]);
    int maxFromEnd[n+1];
    for (int i = 0; i < n+1; i++) {
        maxFromEnd[i] = INT_MIN;
    }
    // create an array maxfromEnd
    for (int i = n - 1; i >= 0; i--) {
        maxFromEnd[i] = max(maxFromEnd[i + 1], v[i]);
    }
 
    int result = 0;
 
    for (int i = 0; i < n; i++) {
        int low = i + 1, high = n - 1, ans = i;
 
        while (low <= high) {
            int mid = (low + high) / 2;
 
            if (v[i] <= maxFromEnd[mid]) {
             
                // We store this as current answer and look
                // for further larger number to the right
                // side
                ans = max(ans, mid);
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
        // keeping a track of the
        // maximum difference in indices
        result = max(result, ans - i);
    }
    printf("\n %d", result);
}
 
/* This code is contributed by Pushpesh Raj */


Java
// Java program to implement
// the above approach
 
// For a given array arr[],
// calculates the maximum j – i
// such that arr[j] > arr[i]
import java.util.*;
class GFG{
 
public static void main(String[] args)
{
  int []v = {34, 8, 10, 3, 2,
             80, 30, 33, 1};
  int n = v.length;
  int []maxFromEnd = new int[n + 1];
  Arrays.fill(maxFromEnd, Integer.MIN_VALUE);
 
  // Create an array maxfromEnd
  for (int i = v.length - 1; i >= 0; i--)
  {
    maxFromEnd[i] = Math.max(maxFromEnd[i + 1],
                             v[i]);
  }
 
  int result = 0;
 
  for (int i = 0; i < v.length; i++)
  {
    int low = i + 1, high = v.length - 1,
        ans = i;
 
    while (low <= high)
    {
      int mid = (low + high) / 2;
 
      if (v[i] <= maxFromEnd[mid])
      {
        // We store this as current
        // answer and look for further
        // larger number to the right side
        ans = Math.max(ans, mid);
        low = mid + 1;
      }
      else
      {
        high = mid - 1;
      }
    }
     
    // Keeping a track of the
    // maximum difference in indices
    result = Math.max(result, ans - i);
  }
  System.out.print(result + "\n");
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program to implement
# the above approach
 
# For a given array arr,
# calculates the maximum j – i
# such that arr[j] > arr[i]
 
# Driver code
if __name__ == '__main__':
   
    v = [34, 8, 10, 3,
         2, 80, 30, 33, 1];
    n = len(v);
    maxFromEnd = [-38749432] * (n + 1);
 
    # Create an array maxfromEnd
    for i in range(n - 1, 0, -1):
        maxFromEnd[i] = max(maxFromEnd[i + 1],
                            v[i]);
 
    result = 0;
 
    for i in range(0, n):
        low = i + 1; high = n - 1; ans = i;
 
        while (low <= high):
            mid = int((low + high) / 2);
 
            if (v[i] <= maxFromEnd[mid]):
               
                # We store this as current
                # answer and look for further
                # larger number to the right side
                ans = max(ans, mid);
                low = mid + 1;
            else:
                high = mid - 1;       
 
        # Keeping a track of the
        # maximum difference in indices
        result = max(result, ans - i);
     
    print(result, end = "");
     
# This code is contributed by Rajput-Ji


C#
// C# program to implement
// the above approach
 
// For a given array []arr,
// calculates the maximum j – i
// such that arr[j] > arr[i]
using System;
class GFG{
 
public static void Main(String[] args)
{
  int []v = {34, 8, 10, 3, 2,
             80, 30, 33, 1};
  int n = v.Length;
  int []maxFromEnd = new int[n + 1];
   
  for (int i = 0;
           i < maxFromEnd.Length; i++)
    maxFromEnd[i] = int.MinValue;
 
  // Create an array maxfromEnd
  for (int i = v.Length - 1;
           i >= 0; i--)
  {
    maxFromEnd[i] = Math.Max(maxFromEnd[i + 1],
                             v[i]);
  }
 
  int result = 0;
 
  for (int i = 0; i < v.Length; i++)
  {
    int low = i + 1,
        high = v.Length - 1,
    ans = i;
 
    while (low <= high)
    {
      int mid = (low + high) / 2;
 
      if (v[i] <= maxFromEnd[mid])
      {
        // We store this as current
        // answer and look for further
        // larger number to the right side
        ans = Math.Max(ans, mid);
        low = mid + 1;
      }
      else
      {
        high = mid - 1;
      }
    }
 
    // Keeping a track of the
    // maximum difference in indices
    result = Math.Max(result, ans - i);
  }
  Console.Write(result + "\n");
}
}
 
// This code is contributed by shikhasingrajput


Javascript


C++
// C++ implementation of
// the hashmap approach
#include 
using namespace std;
 
// Function to find maximum
// index difference
int maxIndexDiff(vector& arr, int n)
{
   
    // Initialise unordered_map
    unordered_map > hashmap;
 
    // Iterate from 0 to n - 1
    for (int i = 0; i < n; i++) {
        hashmap[arr[i]].push_back(i);
    }
 
    // Sort arr
    sort(arr.begin(), arr.end());
    int maxDiff = INT_MIN;
    int temp = n;
   
    // Iterate from 0 to n - 1
    for (int i = 0; i < n; i++) {
        if (temp > hashmap[arr[i]][0]) {
            temp = hashmap[arr[i]][0];
        }
        maxDiff = max(
            maxDiff,
            hashmap[arr[i]][hashmap[arr[i]].size() - 1]
                - temp);
    }
    return maxDiff;
}
 
// Driver Code
int main()
{
 
    int n = 9;
    vector arr{ 34, 8, 10, 3, 2, 80, 30, 33, 1 };
 
    // Function Call
    int ans = maxIndexDiff(arr, n);
    cout << "The maxIndexDiff is : " << ans << endl;
 
    return 1;
}


Java
// Java implementation of
// the hashmap approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to find maximum
// index difference
static int maxIndexDiff(ArrayList arr, int n)
{
     
    // Initialise unordered_map
    Map> hashmap = new HashMap>();
         
    // Iterate from 0 to n - 1
    for(int i = 0; i < n; i++)
    {
        if(hashmap.containsKey(arr.get(i)))
        {
            hashmap.get(arr.get(i)).add(i);
        }
        else
        {
            hashmap.put(arr.get(i), new ArrayList());
            hashmap.get(arr.get(i)).add(i);
        }
    }
     
    // Sort arr
    Collections.sort(arr);
    int maxDiff = Integer.MIN_VALUE;
    int temp = n;
     
    // Iterate from 0 to n - 1
    for(int i = 0; i < n; i++)
    {
        if (temp > hashmap.get(arr.get(i)).get(0))
        {
            temp = hashmap.get(arr.get(i)).get(0);
        }
        maxDiff = Math.max(maxDiff,
        hashmap.get(arr.get(i)).get(
            hashmap.get(arr.get(i)).size() - 1) - temp);
    }
    return maxDiff;
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 9;
    ArrayList arr = new ArrayList(
        Arrays.asList(34, 8, 10, 3, 2, 80, 30, 33, 1));
         
    // Function Call
    int ans = maxIndexDiff(arr, n);
     
    System.out.println("The maxIndexDiff is : " + ans);
}
}
 
// This code is contributed by avanitrachhadiya2155


Python3
# Python3 implementation of the above approach
n = 9
a = [34, 8, 10, 3, 2, 80, 30, 33, 1]
 
# To store the index of an element.
index = dict()
for i in range(n):
    if a[i] in index:
 
        # append to list (for duplicates)
        index[a[i]].append(i) 
    else:
 
        # if first occurrence
        index[a[i]] = [i]  
 
# sort the input array
a.sort()    
maxDiff = 0
 
# Temporary variable to keep track of minimum i
temp = n    
for i in range(n):
    if temp > index[a[i]][0]:
        temp = index[a[i]][0]
    maxDiff = max(maxDiff, index[a[i]][-1]-temp)
 
print(maxDiff)


C#
// C# implementation of
// the hashmap approach
 
using System;
using System.Collections.Generic;
 
public class GFG
{
 
  // Function to find maximum
  // index difference
  static int maxIndexDiff(List arr, int n)
  {
    Dictionary> hashmap = new Dictionary>();
 
    // Iterate from 0 to n - 1
    for(int i = 0; i < n; i++)
    {
      if(hashmap.ContainsKey(arr[i]))
      {
        hashmap[arr[i]].Add(i);
      }
      else
      {
        hashmap.Add(arr[i], new List());
        hashmap[arr[i]].Add(i);
      }
    }
 
    // Sort arr
    arr.Sort();
 
    int maxDiff = -1;
    int temp = n;
 
    // Iterate from 0 to n - 1
    for(int i = 0; i < n; i++)
    {
      if(temp > hashmap[arr[i]][0] )
      {
        temp = hashmap[arr[i]][0];
      }
      maxDiff = Math.Max(maxDiff,hashmap[arr[i]][hashmap[arr[i]].Count - 1]- temp);
    }
    return maxDiff;
  }
   
  // Driver Code
  static public void Main (){
    int n = 9;
    List arr = new List();
    arr.Add(34);
    arr.Add(8);
    arr.Add(10);
    arr.Add(3);
    arr.Add(2);
    arr.Add(80);
    arr.Add(30);
    arr.Add(33);
    arr.Add(1);
     
    // Function Call
    int ans = maxIndexDiff(arr, n);
 
    Console.WriteLine("The maxIndexDiff is : " + ans );
  }
}
 
// This code is contributed by rag2127.


Javascript


C++
#include 
using namespace std;
 
/* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff;
    int i, j;
 
    int* LMin = new int[(sizeof(int) * n)];
    int* RMax = new int[(sizeof(int) * n)];
 
    /* Construct LMin[] such that
    LMin[i] stores the minimum value
    from (arr[0], arr[1], ... arr[i]) */
    LMin[0] = arr[0];
    for (i = 1; i < n; ++i)
        LMin[i] = min(arr[i], LMin[i - 1]);
 
    /* Construct RMax[] such that
    RMax[j] stores the maximum value from
    (arr[j], arr[j+1], ..arr[n-1]) */
    RMax[n - 1] = arr[n - 1];
    for (j = n - 2; j >= 0; --j)
        RMax[j] = max(arr[j], RMax[j + 1]);
 
    /* Traverse both arrays from left to right
    to find optimum j - i. This process is similar to
    merge() of MergeSort */
    i = 0, j = 0, maxDiff = -1;
    while (j < n && i < n) {
        if (LMin[i] <= RMax[j]) {
            maxDiff = max(maxDiff, j - i);
            j = j + 1;
        }
        else
            i = i + 1;
    }
 
    return maxDiff;
}
 
// Driver Code
int main()
{
    int arr[] = { 9, 2, 3, 4, 5,
                  6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    cout << maxDiff;
    return 0;
}
 
// This code is contributed by rathbhupendra


C
#include 
 
/* Utility Functions to get max and minimum of two integers */
int max(int x, int y)
{
    return x > y ? x : y;
}
 
int min(int x, int y)
{
    return x < y ? x : y;
}
 
/* For a given array arr[], returns the maximum j – i such that
    arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff;
    int i, j;
 
    int* LMin = (int*)malloc(sizeof(int) * n);
    int* RMax = (int*)malloc(sizeof(int) * n);
 
    /* Construct LMin[] such that LMin[i] stores the minimum value
       from (arr[0], arr[1], ... arr[i]) */
    LMin[0] = arr[0];
    for (i = 1; i < n; ++i)
        LMin[i] = min(arr[i], LMin[i - 1]);
 
    /* Construct RMax[] such that RMax[j] stores the maximum value
       from (arr[j], arr[j+1], ..arr[n-1]) */
    RMax[n - 1] = arr[n - 1];
    for (j = n - 2; j >= 0; --j)
        RMax[j] = max(arr[j], RMax[j + 1]);
 
    /* Traverse both arrays from left to right to find optimum j - i
        This process is similar to merge() of MergeSort */
    i = 0, j = 0, maxDiff = -1;
    while (j < n && i < n) {
        if (LMin[i] <= RMax[j]) {
            maxDiff = max(maxDiff, j - i);
            j = j + 1;
        }
        else
            i = i + 1;
    }
 
    return maxDiff;
}
 
/* Driver program to test above functions */
int main()
{
    int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    printf("\n %d", maxDiff);
    getchar();
    return 0;
}


Java
class FindMaximum {
    /* Utility Functions to get max and minimum of two integers */
    int max(int x, int y)
    {
        return x > y ? x : y;
    }
 
    int min(int x, int y)
    {
        return x < y ? x : y;
    }
 
    /* For a given array arr[], returns the maximum j-i such that
       arr[j] > arr[i] */
    int maxIndexDiff(int arr[], int n)
    {
        int maxDiff;
        int i, j;
 
        int RMax[] = new int[n];
        int LMin[] = new int[n];
 
        /* Construct LMin[] such that LMin[i] stores the minimum value
           from (arr[0], arr[1], ... arr[i]) */
        LMin[0] = arr[0];
        for (i = 1; i < n; ++i)
            LMin[i] = min(arr[i], LMin[i - 1]);
 
        /* Construct RMax[] such that RMax[j] stores the maximum value
           from (arr[j], arr[j+1], ..arr[n-1]) */
        RMax[n - 1] = arr[n - 1];
        for (j = n - 2; j >= 0; --j)
            RMax[j] = max(arr[j], RMax[j + 1]);
 
        /* Traverse both arrays from left to right to find optimum j - i
           This process is similar to merge() of MergeSort */
        i = 0;
        j = 0;
        maxDiff = -1;
        while (j < n && i < n) {
            if (LMin[i] <= RMax[j]) {
                maxDiff = max(maxDiff, j - i);
                j = j + 1;
            }
            else
                i = i + 1;
        }
 
        return maxDiff;
    }
 
    /* Driver program to test the above functions */
    public static void main(String[] args)
    {
        FindMaximum max = new FindMaximum();
        int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.length;
        int maxDiff = max.maxIndexDiff(arr, n);
        System.out.println(maxDiff);
    }
}


Python3
# Utility Functions to get max
# and minimum of two integers
def max(a, b):
    if(a > b):
        return a
    else:
        return b
 
def min(a, b):
    if(a < b):
        return a
    else:
        return b
 
# For a given array arr[],
# returns the maximum j - i
# such that arr[j] > arr[i]
def maxIndexDiff(arr, n):
    maxDiff = 0;
    LMin = [0] * n
    RMax = [0] * n
 
    # Construct LMin[] such that
    # LMin[i] stores the minimum
    # value from (arr[0], arr[1],
    # ... arr[i])
    LMin[0] = arr[0]
    for i in range(1, n):
        LMin[i] = min(arr[i], LMin[i - 1])
 
    # Construct RMax[] such that
    # RMax[j] stores the maximum
    # value from (arr[j], arr[j + 1],
    # ..arr[n-1])
    RMax[n - 1] = arr[n - 1]
    for j in range(n - 2, -1, -1):
        RMax[j] = max(arr[j], RMax[j + 1]);
 
    # Traverse both arrays from left
    # to right to find optimum j - i
    # This process is similar to
    # merge() of MergeSort
    i, j = 0, 0
    maxDiff = -1
    while (j < n and i < n):
        if (LMin[i] <= RMax[j]):
            maxDiff = max(maxDiff, j - i)
            j = j + 1
        else:
            i = i + 1
 
    return maxDiff
 
# Driver Code
if(__name__ == '__main__'):
    arr = [9, 2, 3, 4, 5,
           6, 7, 8, 18, 0]
    n = len(arr)
    maxDiff = maxIndexDiff(arr, n)
    print (maxDiff)
 
# This code is contributed
# by gautam karakoti


C#
// C# program to find the maximum
// j – i such that arr[j] > arr[i]
using System;
 
class GFG {
    // Utility Functions to get max
    // and minimum of two integers
    static int max(int x, int y)
    {
        return x > y ? x : y;
    }
 
    static int min(int x, int y)
    {
        return x < y ? x : y;
    }
 
    // For a given array arr[], returns
    // the maximum j-i such thatarr[j] > arr[i]
    static int maxIndexDiff(int[] arr, int n)
    {
        int maxDiff;
        int i, j;
 
        int[] RMax = new int[n];
        int[] LMin = new int[n];
 
        // Construct LMin[] such that LMin[i]
        // stores the minimum value
        // from (arr[0], arr[1], ... arr[i])
        LMin[0] = arr[0];
        for (i = 1; i < n; ++i)
            LMin[i] = min(arr[i], LMin[i - 1]);
 
        // Construct RMax[] such that
        // RMax[j] stores the maximum value
        // from (arr[j], arr[j+1], ..arr[n-1])
        RMax[n - 1] = arr[n - 1];
        for (j = n - 2; j >= 0; --j)
            RMax[j] = max(arr[j], RMax[j + 1]);
 
        // Traverse both arrays from left
        // to right to find optimum j - i
        // This process is similar to merge()
        // of MergeSort
        i = 0;
        j = 0;
        maxDiff = -1;
        while (j < n && i < n) {
            if (LMin[i] <= RMax[j]) {
                maxDiff = max(maxDiff, j - i);
                j = j + 1;
            }
            else
                i = i + 1;
        }
 
        return maxDiff;
    }
 
    // Driver program
    public static void Main()
    {
 
        int[] arr = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.Length;
        int maxDiff = maxIndexDiff(arr, n);
        Console.Write(maxDiff);
    }
}
// This Code is Contributed by Sam007


PHP
 arr[i]
 
// For a given array arr[],
// returns the maximum j - i
// such that arr[j] > arr[i]
function maxIndexDiff($arr, $n)
{
    $maxDiff = 0;
    $LMin = array_fill(0, $n, NULL);
    $RMax = array_fill(0, $n, NULL);
 
    // Construct LMin[] such that
    // LMin[i] stores the minimum
    // value from (arr[0], arr[1],
    // ... arr[i])
    $LMin[0] = $arr[0];
    for($i = 1; $i < $n; $i++)
        $LMin[$i] = min($arr[$i],
                        $LMin[$i - 1]);
 
    // Construct RMax[] such that
    // RMax[j] stores the maximum
    // value from (arr[j], arr[j+1],
    // ..arr[n-1])
    $RMax[$n - 1] = $arr[$n - 1];
    for($j = $n - 2; $j >= 0; $j--)
        $RMax[$j] = max($arr[$j],
                        $RMax[$j + 1]);
 
    // Traverse both arrays from left
    // to right to find optimum j - i
    // This process is similar to
    // merge() of MergeSort
    $i = 0;
    $j = 0;
    $maxDiff = -1;
    while ($j < $n && $i < $n)
        if ($LMin[$i] <= $RMax[$j])
        {
            $maxDiff = max($maxDiff, $j - $i);
            $j = $j + 1;
        }
        else
            $i = $i + 1;
 
    return $maxDiff;
}
 
// Driver Code
$arr = array(9, 2, 3, 4, 5,
             6, 7, 8, 18, 0);
$n = sizeof($arr);
$maxDiff = maxIndexDiff($arr, $n);
echo $maxDiff;
 
// This code is contributed
// by ChitraNayal
?>


Javascript


C++
#include 
using namespace std;
 
/* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
 
        int rightMax[n];
        rightMax[n-1]= arr[n-1];
        for(int i = n-2; i>=0; i--)
            rightMax[i] = max(rightMax[i+1] , arr[i]);
         
        //rightMax[i] = max{ arr[i...(n-1] }
 
 
         
        int maxDist = INT_MIN;
        int i = 0, j = 0;
        while(i= arr[i])
            {
                maxDist = max( maxDist, j-i );
                j++;
            }
            else // if(rightMax[j] < leftMin[i])
                i++;
        }
         
        return maxDist;
         
         
}
 
// Driver Code
int main()
{
    int arr[] = { 34,8,10,3,2,80,30,33,1};
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    cout << maxDiff;
    return 0;
}
 
// This code is contributed by Sourashis Mondal


Java
import java.util.*;
 
class GFG{
 
  /* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
  static int maxIndexDiff(int arr[], int n)
  {
 
    int []rightMax = new int[n];
    rightMax[n-1]= arr[n-1];
    for(int i = n-2; i>=0; i--)
      rightMax[i] = Math.max(rightMax[i+1] , arr[i]);
 
    // rightMax[i] = max{ arr[i...(n-1] }
    int maxDist = Integer.MIN_VALUE;
    int i = 0, j = 0;
    while(i < n && j < n)
    {
      if(rightMax[j] >= arr[i])
      {
        maxDist = Math.max( maxDist, j-i );
        j++;
      }
      else // if(rightMax[j] < leftMin[i])
        i++;
    }
 
    return maxDist;
 
 
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = {34, 8, 10, 3, 2, 80, 30, 33, 1};
    int n = arr.length;
    int maxDiff = maxIndexDiff(arr, n);
    System.out.print(maxDiff);
  }
}
 
// This code is contributed by Rajput-Ji


Python3
# For a given array arr[], returns the
# maximum j – i such that arr[j] > arr[i]
def maxIndexDiff(arr, n):
     
    rightMax = [0] * n
    rightMax[n - 1] = arr[n - 1]
    for i in range(n - 2, -1, -1):
        rightMax[i] = max(rightMax[i + 1], arr[i])
         
    # rightMax[i] = max arr[i...(n-1]
    maxDist = -2**31
    i = 0
    j = 0
     
    while (i < n and j < n):
        if (rightMax[j] >= arr[i]):
            maxDist = max(maxDist, j - i)
            j += 1
             
        else:
             
            # if(rightMax[j] < leftMin[i])
            i += 1
     
    return maxDist
 
# Driver Code
arr = [ 34, 8, 10, 3, 2, 80, 30, 33, 1 ]
n = len(arr)
maxDiff = maxIndexDiff(arr, n)
 
print(maxDiff)
 
# This code is contributed by Shubham Singh


C#
/* For a given array arr[], 
returns the maximum j – i such that
arr[j] > arr[i] */
using System;
 
public class GFG
{
 
  static int maxIndexDiff(int[] arr, int n)
  {
  
    int []rightMax = new int[n];
    rightMax[n - 1] = arr[n - 1];
    int i = 0, j = 0;
    for(i = n - 2; i >= 0; i--)
      rightMax[i] = Math.Max(rightMax[i+1] , arr[i]);
 
    // rightMax[i] = max{ arr[i...(n-1] }
    int maxDist = Int32.MinValue;
    i = 0;
    while(i < n && j < n)
    {
      if(rightMax[j] >= arr[i])
      {
        maxDist = Math.Max( maxDist, j - i);
        j++;
      }
      else // if(rightMax[j] < leftMin[i])
        i++;
    }
 
    return maxDist;
  }
 
  // Driver Code
  public static void Main()
  {
    int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};
    int n = arr.Length;
    int maxDiff = maxIndexDiff(arr, n);
    Console.Write(maxDiff);
  }
}
 
// This code is contributed by Shubham Singh


Javascript


C++
#include 
using namespace std;
 
/* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int leftMin[n] ;
    leftMin[0] = arr[0];
    for(int i = 1 ; i=0  &&  j>=0)
    {
        if(arr[j] >= leftMin[i])
        {
            maxDist = max(maxDist, j-i);
            i--;
        }
        else
            j--;
    }
 
    return maxDist;
 
         
}
 
// Driver Code
int main()
{
    int arr[] = { 34,8,10,3,2,80,30,33,1};
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    cout << maxDiff;
    return 0;
}
 
// This code is contributed by Sourashis Mondal


Java
import java.util.*;
class GFG
{
 
  /* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
  static int maxIndexDiff(int arr[], int n)
  {
 
    int []leftMin = new int[n];
    leftMin[0] = arr[0];
    for(int i = 1; i < n; i++)
      leftMin[i] = Math.min(leftMin[i - 1] , arr[i]);
 
    // leftMin[i] = min{ arr[i...(n-1] }
 
    int maxDist = Integer.MIN_VALUE;
    int i = n - 1, j = n - 1;
    while(i >= 0 && j >= 0)
    {
      if(arr[j] >= leftMin[i])
      {
        maxDist = Math.max( maxDist, j - i );
        i--;
      }
      else
        j--;
    }
 
    return maxDist;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = {34, 8, 10, 3, 2, 80, 30, 33, 1};
    int n = arr.length;
    int maxDiff = maxIndexDiff(arr, n);
    System.out.print(maxDiff);
  }
}
 
// This code is contributed by Shubham Singh


Python3
# For a given array arr[], 
#   returns the maximum j – i such that
#   arr[j] > arr[i] */
def maxIndexDiff(arr, n):
     
    leftMin = [0]*n
    leftMin[0] = arr[0]
    for i in range(1,n):
        leftMin[i] = min(leftMin[i-1], arr[i])
         
    # leftMin[i] = min arr[0...i] 
    maxDist = - 2**32
    i = n-1
    j = n-1
     
    while(i>=0  and  j>=0):
         
        if(arr[j] >= leftMin[i]):
            maxDist = max(maxDist, j-i)
            i-=1
        else:
            j-=1
             
    return maxDist
 
# Driver Code
arr = [34,8,10,3,2,80,30,33,1]
n = len(arr)
maxDiff = maxIndexDiff(arr, n)
print(maxDiff)
 
# This code is contributed by Shubham Singh


C#
using System;
 
public class GFG{
 
  /* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
  static int maxIndexDiff(int[] arr, int n)
  {
 
    int []leftMin = new int[n];
    leftMin[0] = arr[0];
    int i,j;
    for( i = 1; i < n; i++)
      leftMin[i] = Math.Min(leftMin[i - 1] , arr[i]);
 
    // leftMin[i] = min{ arr[i...(n-1] }
 
    int maxDist = Int32.MinValue;
    i = n - 1;
    j = n - 1;
    while(i >= 0 && j >= 0)
    {
      if(arr[j] >= leftMin[i])
      {
        maxDist = Math.Max( maxDist, j - i );
        i--;
      }
      else
        j--;
    }
 
    return maxDist;
  }
 
  // Driver Code
  static public void Main ()
  {
    int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};
    int n = arr.Length;
    int maxDiff = maxIndexDiff(arr, n);
    Console.Write(maxDiff);
  }
}
 
// This code is contributed by Shubham Singh


Javascript


输出
8

时间复杂度: O(n^2)

方法 2 –
即兴使用蛮力算法并寻找 BUD,即瓶颈,不必要的和重复的工作。快速观察实际上表明我们一直在寻找从数组末尾遍历到当前索引的第一个最大元素。我们可以看到我们正在尝试为数组中的每个元素一次又一次地找到第一个最大的元素。假设我们有一个数组,例如 [1, 5, 12, 4, 9] 现在我们知道 9 是大于 1、5 和 4 的元素,但是为什么我们需要一次又一次地找到它.我们实际上可以跟踪从数组末尾移动到开头的最大数量。这种方法将帮助我们更好地理解,而且这种即兴创作非常适合在面试中提出。

方法 :

  1. 从末尾遍历数组并跟踪当前索引右侧的最大数字,包括self
  2. 现在我们有一个单调递减数组,我们知道我们可以使用二分搜索来找到最右边的更大元素的索引
  3. 现在我们将只对数组中的每个元素使用二进制搜索并存储索引的最大差异,我们就完成了。

C++

/* For a given array arr[],
   calculates the maximum j – i
   such that arr[j] > arr[i] */
#include 
using namespace std;
 
int main()
{
    vector v{
        34, 8, 10, 3, 2, 80, 30, 33, 1
    };
    int n = v.size();
    vector maxFromEnd(n + 1, INT_MIN);
 
    // create an array maxfromEnd
    for (int i = v.size() - 1; i >= 0; i--) {
        maxFromEnd[i] = max(maxFromEnd[i + 1], v[i]);
    }
 
    int result = 0;
 
    for (int i = 0; i < v.size(); i++) {
        int low = i + 1, high = v.size() - 1, ans = i;
 
        while (low <= high) {
            int mid = (low + high) / 2;
 
            if (v[i] <= maxFromEnd[mid]) {
               
                // We store this as current answer and look
                // for further larger number to the right
                // side
                ans = max(ans, mid);
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
        // keeping a track of the
        // maximum difference in indices
        result = max(result, ans - i);
    }
    cout << result << endl;
}

C

/* C program to implement
the above approach */
 
/* For a given array arr[],
calculates the maximum j – i
such that arr[j] > arr[i] */
#include 
#include 
 
/* Function for maximum of
two numbers in C */
int max(int num1, int num2)
{
    return (num1 > num2 ) ? num1 : num2;
}
 
int main()
{
    int v[] = { 34, 8, 10, 3, 2, 80, 30, 33, 1 };
    int n = sizeof(v) / sizeof(v[0]);
    int maxFromEnd[n+1];
    for (int i = 0; i < n+1; i++) {
        maxFromEnd[i] = INT_MIN;
    }
    // create an array maxfromEnd
    for (int i = n - 1; i >= 0; i--) {
        maxFromEnd[i] = max(maxFromEnd[i + 1], v[i]);
    }
 
    int result = 0;
 
    for (int i = 0; i < n; i++) {
        int low = i + 1, high = n - 1, ans = i;
 
        while (low <= high) {
            int mid = (low + high) / 2;
 
            if (v[i] <= maxFromEnd[mid]) {
             
                // We store this as current answer and look
                // for further larger number to the right
                // side
                ans = max(ans, mid);
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
        // keeping a track of the
        // maximum difference in indices
        result = max(result, ans - i);
    }
    printf("\n %d", result);
}
 
/* This code is contributed by Pushpesh Raj */

Java

// Java program to implement
// the above approach
 
// For a given array arr[],
// calculates the maximum j – i
// such that arr[j] > arr[i]
import java.util.*;
class GFG{
 
public static void main(String[] args)
{
  int []v = {34, 8, 10, 3, 2,
             80, 30, 33, 1};
  int n = v.length;
  int []maxFromEnd = new int[n + 1];
  Arrays.fill(maxFromEnd, Integer.MIN_VALUE);
 
  // Create an array maxfromEnd
  for (int i = v.length - 1; i >= 0; i--)
  {
    maxFromEnd[i] = Math.max(maxFromEnd[i + 1],
                             v[i]);
  }
 
  int result = 0;
 
  for (int i = 0; i < v.length; i++)
  {
    int low = i + 1, high = v.length - 1,
        ans = i;
 
    while (low <= high)
    {
      int mid = (low + high) / 2;
 
      if (v[i] <= maxFromEnd[mid])
      {
        // We store this as current
        // answer and look for further
        // larger number to the right side
        ans = Math.max(ans, mid);
        low = mid + 1;
      }
      else
      {
        high = mid - 1;
      }
    }
     
    // Keeping a track of the
    // maximum difference in indices
    result = Math.max(result, ans - i);
  }
  System.out.print(result + "\n");
}
}
 
// This code is contributed by shikhasingrajput

Python3

# Python3 program to implement
# the above approach
 
# For a given array arr,
# calculates the maximum j – i
# such that arr[j] > arr[i]
 
# Driver code
if __name__ == '__main__':
   
    v = [34, 8, 10, 3,
         2, 80, 30, 33, 1];
    n = len(v);
    maxFromEnd = [-38749432] * (n + 1);
 
    # Create an array maxfromEnd
    for i in range(n - 1, 0, -1):
        maxFromEnd[i] = max(maxFromEnd[i + 1],
                            v[i]);
 
    result = 0;
 
    for i in range(0, n):
        low = i + 1; high = n - 1; ans = i;
 
        while (low <= high):
            mid = int((low + high) / 2);
 
            if (v[i] <= maxFromEnd[mid]):
               
                # We store this as current
                # answer and look for further
                # larger number to the right side
                ans = max(ans, mid);
                low = mid + 1;
            else:
                high = mid - 1;       
 
        # Keeping a track of the
        # maximum difference in indices
        result = max(result, ans - i);
     
    print(result, end = "");
     
# This code is contributed by Rajput-Ji

C#

// C# program to implement
// the above approach
 
// For a given array []arr,
// calculates the maximum j – i
// such that arr[j] > arr[i]
using System;
class GFG{
 
public static void Main(String[] args)
{
  int []v = {34, 8, 10, 3, 2,
             80, 30, 33, 1};
  int n = v.Length;
  int []maxFromEnd = new int[n + 1];
   
  for (int i = 0;
           i < maxFromEnd.Length; i++)
    maxFromEnd[i] = int.MinValue;
 
  // Create an array maxfromEnd
  for (int i = v.Length - 1;
           i >= 0; i--)
  {
    maxFromEnd[i] = Math.Max(maxFromEnd[i + 1],
                             v[i]);
  }
 
  int result = 0;
 
  for (int i = 0; i < v.Length; i++)
  {
    int low = i + 1,
        high = v.Length - 1,
    ans = i;
 
    while (low <= high)
    {
      int mid = (low + high) / 2;
 
      if (v[i] <= maxFromEnd[mid])
      {
        // We store this as current
        // answer and look for further
        // larger number to the right side
        ans = Math.Max(ans, mid);
        low = mid + 1;
      }
      else
      {
        high = mid - 1;
      }
    }
 
    // Keeping a track of the
    // maximum difference in indices
    result = Math.Max(result, ans - i);
  }
  Console.Write(result + "\n");
}
}
 
// This code is contributed by shikhasingrajput

Javascript


输出
6

时间复杂度: O(N*log(N))
空间复杂度: O(N)

方法 3 O(nLgn):
在特别注意重复项后,使用散列和排序以低于二次复杂度的方式解决此问题。
方法 :

  1. 遍历数组并将每个元素的索引存储在列表中(以处理重复项)。
  2. 对数组进行排序。
  3. 现在遍历数组并跟踪 i 和 j 的最大差异。
  4. 对于 j 考虑元素可能索引列表中的最后一个索引,对于 i 考虑列表中的第一个索引。 (因为索引是按升序附加的)。
  5. 继续更新最大差异直到数组结束。

C++

// C++ implementation of
// the hashmap approach
#include 
using namespace std;
 
// Function to find maximum
// index difference
int maxIndexDiff(vector& arr, int n)
{
   
    // Initialise unordered_map
    unordered_map > hashmap;
 
    // Iterate from 0 to n - 1
    for (int i = 0; i < n; i++) {
        hashmap[arr[i]].push_back(i);
    }
 
    // Sort arr
    sort(arr.begin(), arr.end());
    int maxDiff = INT_MIN;
    int temp = n;
   
    // Iterate from 0 to n - 1
    for (int i = 0; i < n; i++) {
        if (temp > hashmap[arr[i]][0]) {
            temp = hashmap[arr[i]][0];
        }
        maxDiff = max(
            maxDiff,
            hashmap[arr[i]][hashmap[arr[i]].size() - 1]
                - temp);
    }
    return maxDiff;
}
 
// Driver Code
int main()
{
 
    int n = 9;
    vector arr{ 34, 8, 10, 3, 2, 80, 30, 33, 1 };
 
    // Function Call
    int ans = maxIndexDiff(arr, n);
    cout << "The maxIndexDiff is : " << ans << endl;
 
    return 1;
}

Java

// Java implementation of
// the hashmap approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to find maximum
// index difference
static int maxIndexDiff(ArrayList arr, int n)
{
     
    // Initialise unordered_map
    Map> hashmap = new HashMap>();
         
    // Iterate from 0 to n - 1
    for(int i = 0; i < n; i++)
    {
        if(hashmap.containsKey(arr.get(i)))
        {
            hashmap.get(arr.get(i)).add(i);
        }
        else
        {
            hashmap.put(arr.get(i), new ArrayList());
            hashmap.get(arr.get(i)).add(i);
        }
    }
     
    // Sort arr
    Collections.sort(arr);
    int maxDiff = Integer.MIN_VALUE;
    int temp = n;
     
    // Iterate from 0 to n - 1
    for(int i = 0; i < n; i++)
    {
        if (temp > hashmap.get(arr.get(i)).get(0))
        {
            temp = hashmap.get(arr.get(i)).get(0);
        }
        maxDiff = Math.max(maxDiff,
        hashmap.get(arr.get(i)).get(
            hashmap.get(arr.get(i)).size() - 1) - temp);
    }
    return maxDiff;
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 9;
    ArrayList arr = new ArrayList(
        Arrays.asList(34, 8, 10, 3, 2, 80, 30, 33, 1));
         
    // Function Call
    int ans = maxIndexDiff(arr, n);
     
    System.out.println("The maxIndexDiff is : " + ans);
}
}
 
// This code is contributed by avanitrachhadiya2155

Python3

# Python3 implementation of the above approach
n = 9
a = [34, 8, 10, 3, 2, 80, 30, 33, 1]
 
# To store the index of an element.
index = dict()
for i in range(n):
    if a[i] in index:
 
        # append to list (for duplicates)
        index[a[i]].append(i) 
    else:
 
        # if first occurrence
        index[a[i]] = [i]  
 
# sort the input array
a.sort()    
maxDiff = 0
 
# Temporary variable to keep track of minimum i
temp = n    
for i in range(n):
    if temp > index[a[i]][0]:
        temp = index[a[i]][0]
    maxDiff = max(maxDiff, index[a[i]][-1]-temp)
 
print(maxDiff)

C#

// C# implementation of
// the hashmap approach
 
using System;
using System.Collections.Generic;
 
public class GFG
{
 
  // Function to find maximum
  // index difference
  static int maxIndexDiff(List arr, int n)
  {
    Dictionary> hashmap = new Dictionary>();
 
    // Iterate from 0 to n - 1
    for(int i = 0; i < n; i++)
    {
      if(hashmap.ContainsKey(arr[i]))
      {
        hashmap[arr[i]].Add(i);
      }
      else
      {
        hashmap.Add(arr[i], new List());
        hashmap[arr[i]].Add(i);
      }
    }
 
    // Sort arr
    arr.Sort();
 
    int maxDiff = -1;
    int temp = n;
 
    // Iterate from 0 to n - 1
    for(int i = 0; i < n; i++)
    {
      if(temp > hashmap[arr[i]][0] )
      {
        temp = hashmap[arr[i]][0];
      }
      maxDiff = Math.Max(maxDiff,hashmap[arr[i]][hashmap[arr[i]].Count - 1]- temp);
    }
    return maxDiff;
  }
   
  // Driver Code
  static public void Main (){
    int n = 9;
    List arr = new List();
    arr.Add(34);
    arr.Add(8);
    arr.Add(10);
    arr.Add(3);
    arr.Add(2);
    arr.Add(80);
    arr.Add(30);
    arr.Add(33);
    arr.Add(1);
     
    // Function Call
    int ans = maxIndexDiff(arr, n);
 
    Console.WriteLine("The maxIndexDiff is : " + ans );
  }
}
 
// This code is contributed by rag2127.

Javascript


输出
The maxIndexDiff is : 6

时间复杂度: O(N*log(N))

方法四(高效)
为了解决这个问题,我们需要得到arr[]的两个最优索引:左索引i和右索引j。对于一个元素 arr[i],如果在 arr[i] 的左侧有一个小于 arr[i] 的元素,我们不需要考虑 arr[i] 作为左索引。类似地,如果 arr[j] 右侧有一个更大的元素,那么我们不需要考虑这个 j 作为右索引。所以我们构造了两个辅助数组 LMin[] 和 RMax[] 使得 LMin[i] 包含 arr[i] 左侧的最小元素,包括 arr[i], RMax[j] 包含右侧的最大元素arr[j] 包括 arr[j]。在构造完这两个辅助数组之后,我们从左到右遍历这两个数组。在遍历 LMin[] 和 RMax[] 时,如果我们看到 LMin[i] 大于 RMax[j],那么我们必须在 LMin[] 中继续前进(或执行 i++),因为 LMin[i] 左侧的所有元素都是大于或等于 LMin[i]。否则,我们必须在 RMax[j] 中前进以寻找更大的 j - i 值。

感谢 celicom 建议此方法的算法。

工作示例:

C++

#include 
using namespace std;
 
/* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff;
    int i, j;
 
    int* LMin = new int[(sizeof(int) * n)];
    int* RMax = new int[(sizeof(int) * n)];
 
    /* Construct LMin[] such that
    LMin[i] stores the minimum value
    from (arr[0], arr[1], ... arr[i]) */
    LMin[0] = arr[0];
    for (i = 1; i < n; ++i)
        LMin[i] = min(arr[i], LMin[i - 1]);
 
    /* Construct RMax[] such that
    RMax[j] stores the maximum value from
    (arr[j], arr[j+1], ..arr[n-1]) */
    RMax[n - 1] = arr[n - 1];
    for (j = n - 2; j >= 0; --j)
        RMax[j] = max(arr[j], RMax[j + 1]);
 
    /* Traverse both arrays from left to right
    to find optimum j - i. This process is similar to
    merge() of MergeSort */
    i = 0, j = 0, maxDiff = -1;
    while (j < n && i < n) {
        if (LMin[i] <= RMax[j]) {
            maxDiff = max(maxDiff, j - i);
            j = j + 1;
        }
        else
            i = i + 1;
    }
 
    return maxDiff;
}
 
// Driver Code
int main()
{
    int arr[] = { 9, 2, 3, 4, 5,
                  6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    cout << maxDiff;
    return 0;
}
 
// This code is contributed by rathbhupendra

C

#include 
 
/* Utility Functions to get max and minimum of two integers */
int max(int x, int y)
{
    return x > y ? x : y;
}
 
int min(int x, int y)
{
    return x < y ? x : y;
}
 
/* For a given array arr[], returns the maximum j – i such that
    arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff;
    int i, j;
 
    int* LMin = (int*)malloc(sizeof(int) * n);
    int* RMax = (int*)malloc(sizeof(int) * n);
 
    /* Construct LMin[] such that LMin[i] stores the minimum value
       from (arr[0], arr[1], ... arr[i]) */
    LMin[0] = arr[0];
    for (i = 1; i < n; ++i)
        LMin[i] = min(arr[i], LMin[i - 1]);
 
    /* Construct RMax[] such that RMax[j] stores the maximum value
       from (arr[j], arr[j+1], ..arr[n-1]) */
    RMax[n - 1] = arr[n - 1];
    for (j = n - 2; j >= 0; --j)
        RMax[j] = max(arr[j], RMax[j + 1]);
 
    /* Traverse both arrays from left to right to find optimum j - i
        This process is similar to merge() of MergeSort */
    i = 0, j = 0, maxDiff = -1;
    while (j < n && i < n) {
        if (LMin[i] <= RMax[j]) {
            maxDiff = max(maxDiff, j - i);
            j = j + 1;
        }
        else
            i = i + 1;
    }
 
    return maxDiff;
}
 
/* Driver program to test above functions */
int main()
{
    int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    printf("\n %d", maxDiff);
    getchar();
    return 0;
}

Java

class FindMaximum {
    /* Utility Functions to get max and minimum of two integers */
    int max(int x, int y)
    {
        return x > y ? x : y;
    }
 
    int min(int x, int y)
    {
        return x < y ? x : y;
    }
 
    /* For a given array arr[], returns the maximum j-i such that
       arr[j] > arr[i] */
    int maxIndexDiff(int arr[], int n)
    {
        int maxDiff;
        int i, j;
 
        int RMax[] = new int[n];
        int LMin[] = new int[n];
 
        /* Construct LMin[] such that LMin[i] stores the minimum value
           from (arr[0], arr[1], ... arr[i]) */
        LMin[0] = arr[0];
        for (i = 1; i < n; ++i)
            LMin[i] = min(arr[i], LMin[i - 1]);
 
        /* Construct RMax[] such that RMax[j] stores the maximum value
           from (arr[j], arr[j+1], ..arr[n-1]) */
        RMax[n - 1] = arr[n - 1];
        for (j = n - 2; j >= 0; --j)
            RMax[j] = max(arr[j], RMax[j + 1]);
 
        /* Traverse both arrays from left to right to find optimum j - i
           This process is similar to merge() of MergeSort */
        i = 0;
        j = 0;
        maxDiff = -1;
        while (j < n && i < n) {
            if (LMin[i] <= RMax[j]) {
                maxDiff = max(maxDiff, j - i);
                j = j + 1;
            }
            else
                i = i + 1;
        }
 
        return maxDiff;
    }
 
    /* Driver program to test the above functions */
    public static void main(String[] args)
    {
        FindMaximum max = new FindMaximum();
        int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.length;
        int maxDiff = max.maxIndexDiff(arr, n);
        System.out.println(maxDiff);
    }
}

Python3

# Utility Functions to get max
# and minimum of two integers
def max(a, b):
    if(a > b):
        return a
    else:
        return b
 
def min(a, b):
    if(a < b):
        return a
    else:
        return b
 
# For a given array arr[],
# returns the maximum j - i
# such that arr[j] > arr[i]
def maxIndexDiff(arr, n):
    maxDiff = 0;
    LMin = [0] * n
    RMax = [0] * n
 
    # Construct LMin[] such that
    # LMin[i] stores the minimum
    # value from (arr[0], arr[1],
    # ... arr[i])
    LMin[0] = arr[0]
    for i in range(1, n):
        LMin[i] = min(arr[i], LMin[i - 1])
 
    # Construct RMax[] such that
    # RMax[j] stores the maximum
    # value from (arr[j], arr[j + 1],
    # ..arr[n-1])
    RMax[n - 1] = arr[n - 1]
    for j in range(n - 2, -1, -1):
        RMax[j] = max(arr[j], RMax[j + 1]);
 
    # Traverse both arrays from left
    # to right to find optimum j - i
    # This process is similar to
    # merge() of MergeSort
    i, j = 0, 0
    maxDiff = -1
    while (j < n and i < n):
        if (LMin[i] <= RMax[j]):
            maxDiff = max(maxDiff, j - i)
            j = j + 1
        else:
            i = i + 1
 
    return maxDiff
 
# Driver Code
if(__name__ == '__main__'):
    arr = [9, 2, 3, 4, 5,
           6, 7, 8, 18, 0]
    n = len(arr)
    maxDiff = maxIndexDiff(arr, n)
    print (maxDiff)
 
# This code is contributed
# by gautam karakoti

C#

// C# program to find the maximum
// j – i such that arr[j] > arr[i]
using System;
 
class GFG {
    // Utility Functions to get max
    // and minimum of two integers
    static int max(int x, int y)
    {
        return x > y ? x : y;
    }
 
    static int min(int x, int y)
    {
        return x < y ? x : y;
    }
 
    // For a given array arr[], returns
    // the maximum j-i such thatarr[j] > arr[i]
    static int maxIndexDiff(int[] arr, int n)
    {
        int maxDiff;
        int i, j;
 
        int[] RMax = new int[n];
        int[] LMin = new int[n];
 
        // Construct LMin[] such that LMin[i]
        // stores the minimum value
        // from (arr[0], arr[1], ... arr[i])
        LMin[0] = arr[0];
        for (i = 1; i < n; ++i)
            LMin[i] = min(arr[i], LMin[i - 1]);
 
        // Construct RMax[] such that
        // RMax[j] stores the maximum value
        // from (arr[j], arr[j+1], ..arr[n-1])
        RMax[n - 1] = arr[n - 1];
        for (j = n - 2; j >= 0; --j)
            RMax[j] = max(arr[j], RMax[j + 1]);
 
        // Traverse both arrays from left
        // to right to find optimum j - i
        // This process is similar to merge()
        // of MergeSort
        i = 0;
        j = 0;
        maxDiff = -1;
        while (j < n && i < n) {
            if (LMin[i] <= RMax[j]) {
                maxDiff = max(maxDiff, j - i);
                j = j + 1;
            }
            else
                i = i + 1;
        }
 
        return maxDiff;
    }
 
    // Driver program
    public static void Main()
    {
 
        int[] arr = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.Length;
        int maxDiff = maxIndexDiff(arr, n);
        Console.Write(maxDiff);
    }
}
// This Code is Contributed by Sam007

PHP

 arr[i]
 
// For a given array arr[],
// returns the maximum j - i
// such that arr[j] > arr[i]
function maxIndexDiff($arr, $n)
{
    $maxDiff = 0;
    $LMin = array_fill(0, $n, NULL);
    $RMax = array_fill(0, $n, NULL);
 
    // Construct LMin[] such that
    // LMin[i] stores the minimum
    // value from (arr[0], arr[1],
    // ... arr[i])
    $LMin[0] = $arr[0];
    for($i = 1; $i < $n; $i++)
        $LMin[$i] = min($arr[$i],
                        $LMin[$i - 1]);
 
    // Construct RMax[] such that
    // RMax[j] stores the maximum
    // value from (arr[j], arr[j+1],
    // ..arr[n-1])
    $RMax[$n - 1] = $arr[$n - 1];
    for($j = $n - 2; $j >= 0; $j--)
        $RMax[$j] = max($arr[$j],
                        $RMax[$j + 1]);
 
    // Traverse both arrays from left
    // to right to find optimum j - i
    // This process is similar to
    // merge() of MergeSort
    $i = 0;
    $j = 0;
    $maxDiff = -1;
    while ($j < $n && $i < $n)
        if ($LMin[$i] <= $RMax[$j])
        {
            $maxDiff = max($maxDiff, $j - $i);
            $j = $j + 1;
        }
        else
            $i = $i + 1;
 
    return $maxDiff;
}
 
// Driver Code
$arr = array(9, 2, 3, 4, 5,
             6, 7, 8, 18, 0);
$n = sizeof($arr);
$maxDiff = maxIndexDiff($arr, $n);
echo $maxDiff;
 
// This code is contributed
// by ChitraNayal
?>

Javascript


输出
8

时间复杂度: O(n)
辅助空间: O(n)

询问:亚马逊、谷歌、VMWare

另一种方法:(仅使用一个额外的数组)

我们考虑一个辅助数组:rightMax[],这样,rightMax[i] = 子数组 arr[i…(n-1)] 的最大元素,arr[i] 元素之后的最大或相等的元素

假设 (arr[i], arr[jLast] ) 是一对,因此 arr[jLast] 是最后一个大于或等于 arr[i] 的元素。对于以 arr[jLast] 结尾的对: ( arr[k], arr[jLast] ) 对于所有 k = (i+1) 到 jLast

我们不需要考虑 (jLast – k),因为 (jLast – i ) > (jLast – k) 对于所有这些 k。

所以我们可以跳过这些对。

从左到右遍历两个数组:arr[] 和 rightMax[],当我们第一次遇到 rightMax[j] < arr[i[ 时,我们知道 jLast = j-1,我们可以跳过对(arr[k ], arr[jLast]) 对于所有 k = (i+1) 到 jLast。

而且rightMax[]是非递增序列,所以rightMax[j]右边的所有元素都小于或等于rightMax[j]。但是在 arr[i] (x > i) 之后可能有 arr[x] 使得 arr[x] < rightMax[j] for x > i,所以当遇到 rightMax[j] < arr[i] 时增加 i。

C++

#include 
using namespace std;
 
/* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
 
        int rightMax[n];
        rightMax[n-1]= arr[n-1];
        for(int i = n-2; i>=0; i--)
            rightMax[i] = max(rightMax[i+1] , arr[i]);
         
        //rightMax[i] = max{ arr[i...(n-1] }
 
 
         
        int maxDist = INT_MIN;
        int i = 0, j = 0;
        while(i= arr[i])
            {
                maxDist = max( maxDist, j-i );
                j++;
            }
            else // if(rightMax[j] < leftMin[i])
                i++;
        }
         
        return maxDist;
         
         
}
 
// Driver Code
int main()
{
    int arr[] = { 34,8,10,3,2,80,30,33,1};
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    cout << maxDiff;
    return 0;
}
 
// This code is contributed by Sourashis Mondal

Java

import java.util.*;
 
class GFG{
 
  /* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
  static int maxIndexDiff(int arr[], int n)
  {
 
    int []rightMax = new int[n];
    rightMax[n-1]= arr[n-1];
    for(int i = n-2; i>=0; i--)
      rightMax[i] = Math.max(rightMax[i+1] , arr[i]);
 
    // rightMax[i] = max{ arr[i...(n-1] }
    int maxDist = Integer.MIN_VALUE;
    int i = 0, j = 0;
    while(i < n && j < n)
    {
      if(rightMax[j] >= arr[i])
      {
        maxDist = Math.max( maxDist, j-i );
        j++;
      }
      else // if(rightMax[j] < leftMin[i])
        i++;
    }
 
    return maxDist;
 
 
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = {34, 8, 10, 3, 2, 80, 30, 33, 1};
    int n = arr.length;
    int maxDiff = maxIndexDiff(arr, n);
    System.out.print(maxDiff);
  }
}
 
// This code is contributed by Rajput-Ji

Python3

# For a given array arr[], returns the
# maximum j – i such that arr[j] > arr[i]
def maxIndexDiff(arr, n):
     
    rightMax = [0] * n
    rightMax[n - 1] = arr[n - 1]
    for i in range(n - 2, -1, -1):
        rightMax[i] = max(rightMax[i + 1], arr[i])
         
    # rightMax[i] = max arr[i...(n-1]
    maxDist = -2**31
    i = 0
    j = 0
     
    while (i < n and j < n):
        if (rightMax[j] >= arr[i]):
            maxDist = max(maxDist, j - i)
            j += 1
             
        else:
             
            # if(rightMax[j] < leftMin[i])
            i += 1
     
    return maxDist
 
# Driver Code
arr = [ 34, 8, 10, 3, 2, 80, 30, 33, 1 ]
n = len(arr)
maxDiff = maxIndexDiff(arr, n)
 
print(maxDiff)
 
# This code is contributed by Shubham Singh

C#

/* For a given array arr[], 
returns the maximum j – i such that
arr[j] > arr[i] */
using System;
 
public class GFG
{
 
  static int maxIndexDiff(int[] arr, int n)
  {
  
    int []rightMax = new int[n];
    rightMax[n - 1] = arr[n - 1];
    int i = 0, j = 0;
    for(i = n - 2; i >= 0; i--)
      rightMax[i] = Math.Max(rightMax[i+1] , arr[i]);
 
    // rightMax[i] = max{ arr[i...(n-1] }
    int maxDist = Int32.MinValue;
    i = 0;
    while(i < n && j < n)
    {
      if(rightMax[j] >= arr[i])
      {
        maxDist = Math.Max( maxDist, j - i);
        j++;
      }
      else // if(rightMax[j] < leftMin[i])
        i++;
    }
 
    return maxDist;
  }
 
  // Driver Code
  public static void Main()
  {
    int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};
    int n = arr.Length;
    int maxDiff = maxIndexDiff(arr, n);
    Console.Write(maxDiff);
  }
}
 
// This code is contributed by Shubham Singh

Javascript


输出
6

时间复杂度:O(n):由于 i 和 j 指针最多遍历 n 个元素,时间复杂度 = O(n) + O(n) = O(n)

空间复杂度:O(n)

使用 leftMin[] :

我们也可以只使用 leftMin[] 数组来做到这一点,其中 leftMin[i] = 子数组 arr[0…i] 的最小元素

C++

#include 
using namespace std;
 
/* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int leftMin[n] ;
    leftMin[0] = arr[0];
    for(int i = 1 ; i=0  &&  j>=0)
    {
        if(arr[j] >= leftMin[i])
        {
            maxDist = max(maxDist, j-i);
            i--;
        }
        else
            j--;
    }
 
    return maxDist;
 
         
}
 
// Driver Code
int main()
{
    int arr[] = { 34,8,10,3,2,80,30,33,1};
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    cout << maxDiff;
    return 0;
}
 
// This code is contributed by Sourashis Mondal

Java

import java.util.*;
class GFG
{
 
  /* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
  static int maxIndexDiff(int arr[], int n)
  {
 
    int []leftMin = new int[n];
    leftMin[0] = arr[0];
    for(int i = 1; i < n; i++)
      leftMin[i] = Math.min(leftMin[i - 1] , arr[i]);
 
    // leftMin[i] = min{ arr[i...(n-1] }
 
    int maxDist = Integer.MIN_VALUE;
    int i = n - 1, j = n - 1;
    while(i >= 0 && j >= 0)
    {
      if(arr[j] >= leftMin[i])
      {
        maxDist = Math.max( maxDist, j - i );
        i--;
      }
      else
        j--;
    }
 
    return maxDist;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = {34, 8, 10, 3, 2, 80, 30, 33, 1};
    int n = arr.length;
    int maxDiff = maxIndexDiff(arr, n);
    System.out.print(maxDiff);
  }
}
 
// This code is contributed by Shubham Singh

Python3

# For a given array arr[], 
#   returns the maximum j – i such that
#   arr[j] > arr[i] */
def maxIndexDiff(arr, n):
     
    leftMin = [0]*n
    leftMin[0] = arr[0]
    for i in range(1,n):
        leftMin[i] = min(leftMin[i-1], arr[i])
         
    # leftMin[i] = min arr[0...i] 
    maxDist = - 2**32
    i = n-1
    j = n-1
     
    while(i>=0  and  j>=0):
         
        if(arr[j] >= leftMin[i]):
            maxDist = max(maxDist, j-i)
            i-=1
        else:
            j-=1
             
    return maxDist
 
# Driver Code
arr = [34,8,10,3,2,80,30,33,1]
n = len(arr)
maxDiff = maxIndexDiff(arr, n)
print(maxDiff)
 
# This code is contributed by Shubham Singh

C#

using System;
 
public class GFG{
 
  /* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
  static int maxIndexDiff(int[] arr, int n)
  {
 
    int []leftMin = new int[n];
    leftMin[0] = arr[0];
    int i,j;
    for( i = 1; i < n; i++)
      leftMin[i] = Math.Min(leftMin[i - 1] , arr[i]);
 
    // leftMin[i] = min{ arr[i...(n-1] }
 
    int maxDist = Int32.MinValue;
    i = n - 1;
    j = n - 1;
    while(i >= 0 && j >= 0)
    {
      if(arr[j] >= leftMin[i])
      {
        maxDist = Math.Max( maxDist, j - i );
        i--;
      }
      else
        j--;
    }
 
    return maxDist;
  }
 
  // Driver Code
  static public void Main ()
  {
    int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};
    int n = arr.Length;
    int maxDiff = maxIndexDiff(arr, n);
    Console.Write(maxDiff);
  }
}
 
// This code is contributed by Shubham Singh

Javascript


输出
6