Friday, 18 December 2020

Write a program to print nearest greater number along with each number in a given list

   github: https://github.com/prasune/Algorithms/tree/master/src/main/java/com/test/algorithm/stack

Nearest greater number is not the next greater number.

For example - for a given input - {4,2,5,8,12,11,10}

output will be like:

2 -> 5

4 -> 5

5 -> 8

8 -> 12

10 -> -1

11 -> -1

12 -> -1


package com.test.algorithm.stack;

import java.util.Stack;

public class NearestGreaterNumber {

public static void main(String[] args) {
int[] numArray = new int[]{4,2,5,8,12,11,10};
printNumWithNearestGreaterNumber(numArray);
}

private static void printNumWithNearestGreaterNumber(int[] numArray) {
Stack<Integer> numStack = new Stack<>();
for (int i=0; i< numArray.length; i++) {
while (!numStack.isEmpty() && numStack.peek() < numArray[i]) {
System.out.println(numStack.pop() + " -> " + numArray[i]);
}
numStack.push(numArray[i]);
}
while (!numStack.isEmpty()) {
System.out.println(numStack.pop() + " -> -1");
}
}
}

No comments:

Post a Comment