Max Value of Equation (LeetCode 1499): Solution and Explanation

Hard
Array
Sliding Window
Heap
Queue
Monotonic Queue

Points are given sorted by x. For pairs i < j whose x values differ by at most k, compute yi + yj + |xi - xj| and return the largest value. At least one valid pair is guaranteed to exist.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force checks every pair, which is O(n²) and too slow for 10^5 points. The absolute value looks like the obstacle, but since the points are sorted by x and i < j, we know xj >= xi, so |xi - xj| is simply xj - xi. The expression becomes yi + yj + xj - xi, which splits cleanly into a part that depends only on j, yj + xj, and a part that depends only on i, yi - xi.

So for each j we want the largest yi - xi among earlier points with xj - xi <= k. That is a maximum over a sliding window: as j moves right, the window gains a new point on the right and loses points on the left whose x is now too far away. A heap works, but there is an O(n) structure tailored for sliding window maximums, the monotonic deque.

The deque stores pairs (yi - xi, xi) with the yi - xi values strictly decreasing from front to back. The front is always the best candidate in the window. Before using it for point j, pop from the front any point whose x is more than k away. After using it, add point j as a candidate for future points, first popping from the back every entry whose value is less than or equal to yj - xj. Those entries are older and no better, so they can never be the maximum again. Each point enters and leaves the deque at most once.

Approach: Monotonic deque over a sliding window

  1. Keep a deque of (yi - xi, xi) pairs in decreasing order of yi - xi, and set result to negative infinity.
  2. For each point (xj, yj), pop from the front while xj - dq[0][1] > k, removing points that are too far left.
  3. If the deque is not empty, update result with yj + xj + dq[0][0], the best partner for this point.
  4. Pop from the back while the last value is at most yj - xj, since the new point dominates it.
  5. Append (yj - xj, xj) to the back.
  6. Return result after processing every point.

Step-by-step example

points = [[1,3], [2,0], [5,10], [6,-10]], k = 1
  1. Point (1,3): the deque is empty, so there is no pair yet. Push (3 - 1, 1) = (2, 1).
  2. Point (2,0): the front has x = 1 and 2 - 1 = 1 is within k. Candidate 0 + 2 + 2 = 4, so result = 4. Push (-2, 2) behind (2, 1).
  3. Point (5,10): both entries are too far (5 - 1 = 4 and 5 - 2 = 3 exceed 1), so the deque empties. No candidate. Push (5, 5).
  4. Point (6,-10): the front (5, 5) is within range, candidate -10 + 6 + 5 = 1, which does not beat 4. Push (-16, 6).
  5. The answer is 4, from points (1,3) and (2,0): 3 + 0 + 1.

Code: Python, Java, C++

1class Solution:
2    def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:
3        from collections import deque
4        # We want to maximize yi + yj + xj - xi = (yj + xj) + (yi - xi)
5        # For each j, we want max(yi - xi) where xj - xi <= k
6        dq = deque()  # stores (yi - xi, xi)
7        result = float('-inf')
8
9        for xj, yj in points:
10            # Remove points outside window
11            while dq and xj - dq[0][1] > k:
12                dq.popleft()
13
14            # Calculate max value with current point
15            if dq:
16                result = max(result, yj + xj + dq[0][0])
17
18            # Maintain decreasing monotonic queue
19            while dq and dq[-1][0] <= yj - xj:
20                dq.pop()
21            dq.append((yj - xj, xj))
22
23        return result

Time and space complexity

Time

O(n)

Each point is appended once and removed at most once from either end of the deque, so the total work is linear.

Space

O(n)

In the worst case, such as strictly decreasing y - x values within one window, the deque holds every point.

Other approaches

Max heap with lazy deletion (time O(n log n), space O(n))

Push (yi - xi, xi) into a max heap and, for each j, pop from the top while the top's x is out of range before using it. Stale entries are discarded only when they reach the top. It is simpler to reason about than the deque and still fast.

Common mistakes

  • Adding point j to the deque before computing its answer, which can pair a point with itself.
  • Keeping yi + xi instead of yi - xi in the deque, which gets the sign of the distance term wrong.
  • Initializing result to 0, which fails when every valid pair has a negative value.
  • Evicting out-of-range points after reading the front instead of before, which pairs point j with a point whose x is more than k away.

Frequently asked questions

How do you get rid of the absolute value in Max Value of Equation?

Points are sorted by x and i < j, so xj is at least xi and the absolute value equals xj - xi. The expression then separates into (yj + xj) + (yi - xi).

Why does a monotonic deque work here?

We need the maximum of yi - xi over a window that slides right. Any older point with a value no larger than a newer one can never be the answer again, so the deque discards it and keeps the front as the current maximum.

Heap or deque for this problem?

Both are accepted. The deque is O(n) and the heap is O(n log n), but the heap is often easier to write correctly under pressure.