Maximum the value of a given expression for any pair of coordinates on a 2D plane | Java program for the above approach ; Function to find the maximum value of the given expression possible for any pair of co - ordinates ; Stores the differences between pairs ; Stores the maximum value ; Traverse the array arr [ ] [ ] ; While pq is not empty and difference between point [ 0 ] and pq . top ( ) [ 1 ] > K ; Removes the top element ; If pq is not empty ; Update the value res ; Push pair { point [ 1 ] - point [ 0 ] , point [ 0 ] } in pq ; Print the result ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static void findMaxValueOfEquation ( int arr [ ] [ ] , int K ) { PriorityQueue < int [ ] > pq = new PriorityQueue < > ( ( a , b ) -> { if ( a [ 0 ] != b [ 0 ] ) return b [ 0 ] - a [ 0 ] ; return b [ 1 ] - a [ 1 ] ; } ) ; int res = Integer . MIN_VALUE ; for ( int point [ ] : arr ) { while ( ! pq . isEmpty ( ) && point [ 0 ] - pq . peek ( ) [ 1 ] > K ) { pq . poll ( ) ; } if ( ! pq . isEmpty ( ) ) { res = Math . max ( res , pq . peek ( ) [ 0 ] + point [ 0 ] + point [ 1 ] ) ; } pq . add ( new int [ ] { point [ 1 ] - point [ 0 ] , point [ 0 ] } ) ; } System . out . println ( res ) ; } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 1 , 3 } , { 2 , 0 } , { 5 , 10 } , { 6 , - 10 } } ; int K = 1 ; findMaxValueOfEquation ( arr , K ) ; } }