1499. Max Value of Equation
You are given an array points
containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi]
such that xi < xj
for all 1 <= i < j <= points.length
. You are also given an integer k
.
Return the maximum value of the equation yi + yj + |xi - xj|
where |xi - xj| <= k
and 1 <= i < j <= points.length
.
It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k
.
Example 1:
Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
Output: 4
Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
Example 2:
Input: points = [[0,0],[3,0],[9,2]], k = 3
Output: 3
Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
Constraints:
2 <= points.length <= 105
points[i].length == 2
-108 <= xi, yi <= 108
0 <= k <= 2 * 108
xi < xj
for all1 <= i < j <= points.length
xi
form a strictly increasing sequence.
Solution
Brute force
iterate all possible combinations and find a max among them
Time Complexity: O(N^2), N is the number of input points
Enhancement: Remove duplicated computation -> checking point (i, j) is equal to checking points (j, i)
Time Complexity: O(N^2/2)
Enhacement2:
The input points are sorted, so For all (i, j) in [0....N-1], if j > i, then Xj >= Xi
yi + yj + |xi - xj| = yi + yj + xj - xi = (xj+yj) + (yi - xi)
-> If we can find the i, which (yi - xi) is the max, then we found it!
Ticky part: Becuase we only want to find the pair, so we can fixed at point j, and search for i,
where yi - xi is max, and xj - xi is <= k,
And, we don't need to checking all the combination when we fixed at i, we can check elements before i only([0...i-1], i), and the other combination (i, [i+1...N-1]) can be checked in the next fixed elements.
How to find the element which can result in the max or min result? Heap
public int findMax(int[][] points, int k){
int ret = Integer.MIN_VALUE;
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a,b) -> Integer.compare(b[1]-b[0], a[1]-a[0]));
for(int[] point : points){
while(!maxHeap.isEmpty() && point[0] - maxHeap.peek()[0] > k){
maxHeap.poll();
}
if(!maxHeap.isEmpty()){
ret = Math.max(ret, point[0] + point[1] + maxHeap.peek()[1] - maxHeap.peek()[0]);
}
maxHeap.add(point);
}
return ret;
}
Last updated
Was this helpful?