Maximum the value of a given expression for any pair of coordinates on a 2D plane
Last Updated :
10 Jan, 2023
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++
#include <bits/stdc++.h>
using namespace std;
void findMaxValueOfEquation(
vector<vector< int > >& arr, int K)
{
priority_queue<vector< int > > pq;
int res = INT_MIN;
for ( auto point : arr) {
while (!pq.empty()
&& point[0] - pq.top()[1]
> K) {
pq.pop();
}
if (!pq.empty()) {
res = max(res,
pq.top()[0] + point[0] + point[1]);
}
pq.push({ point[1] - point[0],
point[0] });
}
cout << res;
}
int main()
{
vector<vector< int > > arr
= { { 1, 3 }, { 2, 0 },
{ 5, 10 }, { 6, -10 } };
int K = 1;
findMaxValueOfEquation(arr, K);
return 0;
}
|
Java
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);
}
}
|
Python3
def findMaxValueOfEquation(arr, K):
pq = []
res = - 10 * * 8
for point in arr:
while ( len (pq)> 0 and point[ 0 ] - pq[ - 1 ][ 1 ] > K):
del pq[ - 1 ]
if ( len (pq) > 0 ):
res = max (res, pq[ - 1 ][ 0 ] + point[ 0 ] + point[ 1 ])
pq.append([point[ 1 ] - point[ 0 ], point[ 0 ]])
pq = sorted (pq)
print (res)
if __name__ = = '__main__' :
arr = [ [ 1 , 3 ], [ 2 , 0 ], [ 5 , 10 ], [ 6 , - 10 ] ]
K = 1
findMaxValueOfEquation(arr, K)
|
C#
using System;
using System.Collections.Generic;
class Program {
static void FindMaxValueOfEquation( int [][] arr, int K)
{
var pq = new SortedSet< int []>(
Comparer< int []>.Create((a, b) => {
if (a[0] != b[0]) {
return b[0] - a[0];
}
return b[1] - a[1];
}));
int res = int .MinValue;
foreach ( int [] point in arr)
{
while (pq.Count > 0
&& point[0] - pq.Min[1] > K) {
pq.Remove(pq.Min);
}
if (pq.Count > 0) {
res = Math.Max(res, pq.Min[0] + point[0]
+ point[1]);
}
pq.Add( new int [] { point[1] - point[0],
point[0] });
}
Console.WriteLine(res);
}
static void Main( string [] args)
{
int [][] arr
= { new int [] { 1, 3 }, new int [] { 2, 0 },
new int [] { 5, 10 }, new int [] { 6, -10 } };
int K = 1;
FindMaxValueOfEquation(arr, K);
}
}
|
Javascript
<script>
function findMaxValueOfEquation(arr,K)
{
let pq=[];
let res = Number.MIN_VALUE;
for (let point=0;point< arr.length;point++) {
while (pq.length!=0
&& arr[point][0] - pq[0][1] > K) {
pq.shift();
}
if (pq.length!=0) {
res = Math.max(res, pq[0][0] + arr[point][0]
+ arr[point][1]);
}
pq.push([ arr[point][1] - arr[point][0],
arr[point][0] ]);
pq.sort( function (a,b){
if (a[0] != b[0])
return b[0] - a[0];
return b[1] - a[1];})
}
document.write(res);
}
let arr = [[ 1, 3 ], [ 2, 0 ], [ 5, 10 ], [ 6, -10 ]];
let K = 1;
findMaxValueOfEquation(arr, K);
</script>
|
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...