Problem
Given an array a of n positive integers. The task is to find the maximum of j - i subject to the constraint of a[i] <= a[j] and i <= j.
Examples
Example 1
n = 2
a[] = {1, 10}
Output: 1 (a[1] >= a[0])
Example 2
n = 9
a[] = {34, 8, 10, 3, 2, 80, 30, 33, 1}
Output: 6 (a[7] >= a[1])
Complexity Constraints
Time complexity: O(N)
Auxiliary space: O(N)
Parameter Constraints
1 <= n <= 10 ^ 6
0 <= a[i] <= 10 ^ 9
Answer (in Java)
2024年3月5日,于印度尼西亚巴厘岛
/* By LI YI CHEN on 2024/3/5, in BALI Indonesia */
import java.util.Scanner;
public class Maximum_Index
{
public static void main(String[] args)
{
int n, i;
int temp;
int[] arr = new int[1000001];
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter n:");
n = scanner.nextInt();
System.out.println("Enter n elements for array: ");
for (i = 0; i < n; i++)
{
arr[i] = scanner.nextInt();
}
int j, k; // pointer variables
int maximum_index = 0; // the answer, initialized to 0
// Core code
for (j = 0;j <= n - 1;j ++)
{
for (k = n - 1;k >= j;k --)
{
if (arr[k] >= arr[j] && k - j > maximum_index)
{
maximum_index = k - j;
}
}
}
System.out.println("The required maximum index is: " + maximum_index);
System.out.println("Program finished. Good day.");
}
}
运行示例
示例1:
示例2:
思路简述
本题的解题思路比较简洁直观:定义2个指针 j 和 k,其中 j 从数组的头部开始迭代自增,k 从数组的末尾(由于题目要求最大的索引差,从末尾开始会比较快)迭代自减,满足条件则更新答案变量Maximum_Index,最后将Maximum_Index输出即可。核心代码由一个2次嵌套的for循环构成:
int maximum_index = 0; // the answer, initialized to 0
// Core code
for (j = 0;j <= n - 1;j ++)
{
for (k = n - 1;k >= j;k --)
{
if (arr[k] >= arr[j] && k - j > maximum_index)
{
maximum_index = k - j;
}
}
}