Skip to problem
←

Max Value of Equation

Hard 0 attempts

You're given an array points of 2D coordinates, already sorted by their x-values, plus an integer k. Among all index pairs i < j whose x-values satisfy |xi - xj| <= k, find the largest possible result of the expression yi + yj + |xi - xj|.

Return the maximum numerical value, not the chosen pair. The distance limit is inclusive, the two points must be distinct, and at least one valid pair is guaranteed. Negative answers are allowed.

Function contract

Implement findMaxValueOfEquation(points, k). Receive [x, y] pairs in strictly increasing x order and a positive distance limit. At least one valid pair exists.

Output: Return the maximum equation value over distinct points with x-distance at most k. The answer may be negative.

Example 1

Input
points = [[1,3],[2,0],[5,10],[6,-10]]
k = 1
Output
4

Example 2

Input
points = [[0,0],[3,0],[4,10]]
k = 1
Output
11
Constraints
  • 2 <= points.length <= 10^5
  • -10^8 <= xi, yi <= 10^8
  • x coordinates are strictly increasing.
  • 1 <= k <= 2 * 10^8
  • At least one pair satisfies the distance condition.

Maximize (yi + yj) + |xi - xj|. Since points are sorted by x, this simplifies to maximizing (yj + xj) + (yi - xi) where j > i. Use a deque to maintain the maximum yi - xi for points within x-distance k.

The active deque is the slice starting at head. Remove expired points from its front and weaker candidates from its back, never popping behind head. A newer point with at least as large a y - x dominates an older point because it also expires no earlier. Evaluate the current point before inserting it so the two points are distinct.

javascript
function findMaxValueOfEquation(points, k) {
  const deque = []; let head = 0;
  let result = -Infinity;

  for (const [xj, yj] of points) {
    while (deque.length > head && xj - deque[head][1] > k) {
      head++;
    }

    if (deque.length > head) {
      result = Math.max(result, yj + xj + deque[head][0]);
    }

    const val = yj - xj;
    while (deque.length > head && deque[deque.length - 1][0] <= val) {
      deque.pop();
    }
    deque.push([val, xj]);
  }

  return result;
}

Time: O(n) Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript