Find the closest greater element for arr [ j ] in the entire array .
let diff = Number . MAX_VALUE ; let closest = - 1 ; for ( let j = 0 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] && arr [ j ] - arr [ i ] < diff ) { diff = arr [ j ] - arr [ i ] ; closest = j ; } }