Untitled
unknown
plain_text
3 years ago
1.0 kB
8
Indexable
package test;
import java.util.Scanner;
public class Solution {
public static int[] findClosest(int[] arr, int n) {
int res[] = new int[n];
res[n - 1] = -1;
for (int i = n - 2; i >= 0; i--) {
int j = i + 1;
while (j != -1 && arr[j] > arr[i]) {
j = res[j];
}
res[i] = j;
}
for (int i = 0; i < n; i++) {
if (res[i] != -1) {
res[i] = arr[res[i]];
}
}
return res;
}
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();
}
sc.close();
int res[] = findClosest(arr, n);
for (int i = 0; i < n; i++) {
System.out.print(res[i] + " ");
}
System.out.println();
}
}Editor is loading...