Skip to content
Related Articles

Related Articles

Improve Article
Maximum the value of a given expression for any pair of coordinates on a 2D plane
  • Last Updated : 06 May, 2021

Given a sorted 2D array arr[][2] of size N such that (arr[i][0], arr[i][1]) represents the coordinates of ith point in the cartesian plane and an integer K, the task is to find the maximum value of the expression (|arr[i][0] – arr[j][0]| + arr[i][1] + arr[j][1]) such that |arr[i][0] – arr[j][0]| ≤ K for any possible pair of coordinates (i, j).

Examples:

Input: arr[][] = {{1, 3}, {2, 0}, {5, 10}, {6, -10}}, K = 1
Output: 4
Explanation:
Choose pairs (0, 1). Now the value of the expression is given by:
value = (abs(1 – 2) + 3 + 0) = 4, which is maximum and abs(1 – 2) = 1(≤ K).
Therefore, print 4.

Input: arr[][] = {{0, 0}, {3, 0}, {9, 2}}, K = 3
Output: 3

Approach: The given problem can be solved using a Greedy Algorithm using the priority queue which is based on the following observations: 



  • Rearranging the expression for all i > j as (arr[i][0] – arr[i][1] + arr[j][0] + arr[j][1]).
  • Now, keeping the pair of {arr[i]x – arr[i]y, arr[i]x} in sorted order, the value of the given expression for every array element at index j can be calculated.

Follow the steps below to solve the problem:

  • Initialize a priority_queue of pairs say PQ that stores the pair of differences of coordinated axes of a point and X coordinate of that point.
  • Initialize a variable say res as INT_MIN to store the maximum value.
  • Traverse the array arr[][] and considering {X, Y} is the current point perform the following operations:
    • Iterate while PQ is not empty and (X – PQ.top()[1]) is greater than K and remove the top element from the priority_queue PQ.
    • If PQ is not empty then update the value of res as the maximum of res and PQ.top()[0] + X + Y).
    • Push the pair {Y – X, X} into the priority_queue PQ.
  • After completing the above steps, print the value of res as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum value
// of the given expression possible
// for any pair of co-ordinates
void findMaxValueOfEquation(
    vector<vector<int> >& arr, int K)
{
    // Stores the differences between pairs
    priority_queue<vector<int> > pq;
 
    // Stores the maximum value
    int res = INT_MIN;
 
    // Traverse the array arr[][]
    for (auto point : arr) {
 
        // While pq is not empty and
        // difference between point[0]
        // and pq.top()[1] > K
        while (!pq.empty()
               && point[0] - pq.top()[1]
                      > K) {
 
            // Removes the top element
            pq.pop();
        }
 
        // If pq is not empty
        if (!pq.empty()) {
 
            // Update the value res
            res = max(res,
                      pq.top()[0] + point[0] + point[1]);
        }
 
        // Push pair {point[1] - point[0],
        // point[0]} in pq
        pq.push({ point[1] - point[0],
                  point[0] });
    }
 
    // Print the result
    cout << res;
}
 
// Driver Code
int main()
{
    vector<vector<int> > arr
        = { { 1, 3 }, { 2, 0 },
            { 5, 10 }, { 6, -10 } };
    int K = 1;
    findMaxValueOfEquation(arr, K);
 
    return 0;
}

Java




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

Python3




# Python3 program for the above approach
 
# Function to find the maximum value
# of the given expression possible
# for any pair of co-ordinates
def findMaxValueOfEquation(arr, K):
   
    # Stores the differences between pairs
    pq = []
 
    # Stores the maximum value
    res = -10**8
 
    # Traverse the array arr[][]
    for point in arr:
 
        # While pq is not empty and
        # difference between point[0]
        # and pq.top()[1] > K
        while (len(pq)>0 and point[0] - pq[-1][1] > K):
           
            # Removes the top element
            del pq[-1]
 
        # If pq is not empty
        if (len(pq) > 0):
            # Update the value res
            res = max(res, pq[-1][0] + point[0] + point[1])
 
        # Push pair {point[1] - point[0],
        # point[0]} in pq
        pq.append([point[1] - point[0], point[0]])
        pq = sorted(pq)
 
    # Prthe result
    print (res)
 
# Driver Code
if __name__ == '__main__':
    arr = [ [ 1, 3 ], [ 2, 0 ], [ 5, 10 ], [ 6, -10 ] ]
    K = 1
    findMaxValueOfEquation(arr, K)
 
# This code is contributed by mohit kumar 29.
Output: 
4

 

Time Complexity: O(N * log N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :