text: Java implementation of the approach
code: import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . Stack ; class GFG { static class Pair { int first , second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } }