Max Value of Equation Problem
Description
LeetCode Problem 1499.
You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [x_i, y_i] such that x_i < x_j for all 1 <= i < j <= points.length. You are also given an integer k.
Return the maximum value of the equation y_i + y_j + |x_i - x_j| where |x_i - x_j| <= k and 1 <= i < j <= points.length.
It is guaranteed that there exists at least one pair of points that satisfy the constraint |x_i - x_j| <= 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 |x_i - x_j| <= 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 <= 10^5points[i].length == 2-10^8 <= x_i, y_i <= 10^80 <= k <= 2 * 10^8x_i < x_jfor all1 <= i < j <= points.lengthx_iform a strictly increasing sequence.
Solution
Approach: Monotonic Deque
Because the points are sorted by x, for i < j we have |x_i - x_j| = x_j - x_i, and the value splits into a part for each point:
y_i + y_j + x_j - x_i = (x_j + y_j) + (y_i - x_i)
So for every point j we want the largest y_i - x_i among earlier points with x_j - x_i <= k. That is a sliding-window maximum, and a deque handles it:
- Keep earlier points in the deque with their
y - xvalues decreasing from front to back. - Before using point
j, drop points from the front whilex_j - x_front > k. They are too far left forj, and sincexonly grows, for every later point too. - If the deque is not empty, its front has the largest
y - xin the window: tryx_j + y_j + (y_front - x_front). - Before adding
j, drop points from the back whosey - xis at mosty_j - x_j. Pointjis better than them and stays in the window longer, so they can never be the best again.
Pairs must use two different points, which is why we compute the candidate before adding j to the deque. Values can be negative, so start the answer at minus infinity, not 0; the problem guarantees at least one valid pair.
Complexity: O(n) time, since each point enters and leaves the deque at most once, and O(n) space.
from collections import deque
class Solution:
def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:
ans = float("-inf")
q = deque() # earlier points (x, y - x), with y - x decreasing from front to back
for x, y in points:
while q and x - q[0][0] > k:
q.popleft() # too far to the left for this and every later point
if q:
ans = max(ans, x + y + q[0][1])
while q and q[-1][1] <= y - x:
q.pop() # never better than the current point again
q.append((x, y - x))
return ans