This is my code complexity O(n). I have used recursion inside a loop.
package Section11_OopsAndStacks;
public class NextGreaterElement {
public static void main(String[] args) {
int[] arr = { 2, 1, 3, 8, 6, 7, 5 };
for (int i = 0; i < arr.length; i++) {
int num = arr[i];
nextGreaterElement(arr, i + 1, num);
}
}
public static void nextGreaterElement(int[] arr, int index, int currele) {
if (index == arr.length) {
System.out.println(currele + "->-1");
return;
}
if (arr[index] > currele) {
System.out.println(currele + "->" + arr[index]);
return;
}
if (arr[index] < currele) {
nextGreaterElement(arr, index + 1, currele);
}
}
}