-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum_Index.java
44 lines (37 loc) · 1006 Bytes
/
Maximum_Index.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.*;
class Maximum_Index {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println(maxIndexDiff(arr, n));
}
static int maxIndexDiff(int arr[], int n) {
// Time comp: O(n^2);
// int diff=0;
// for(int i=0;i<n;i++){
// for(int j=0;j<n;j++){
// if(arr[i]<=arr[j]){
// diff=Math.max(j-i,diff);
// }
// }
// }
// return diff;
// optimised O(n)
int i = 0, j = n - 1;
int maxi = 0;
while (i < j) {
if (arr[j] >= arr[i]) {
maxi = Math.max(maxi, j - i);
i++;
j = n - 1;
} else {
j--;
}
}
return maxi;
}
}