Java implementation of the approach
import java . util . ArrayList ; import java . util . Arrays ; import java . util . PriorityQueue ; class Pair < K , V > { K first ; V second ; public Pair ( K first , V second ) { this . first = first ; this . second = second ; } } class GFG { static final float inf = Float . POSITIVE_INFINITY ;