Max Value of Equation

HardMonotonic Deque · Sliding Window🧩 Queue & Monotonic DequeLeetCode #1499 ↗Updated

Problem

You get 2D points whose x-coordinates are strictly increasing, plus an integer k. Among all pairs i < j with xj - xi ≤ k, return the largest value of yi + yj + |xi - xj|. At least one valid pair is guaranteed to exist.
Inputpoints=[[1,3],[2,0],[5,10],[6,-10]], k=1Output4
Inputpoints=[[0,0],[3,0],[9,2]], k=3Output3

2 ≤ n ≤ 105  ·  -108 ≤ x, y ≤ 108  ·  0 ≤ k ≤ 2·108  ·  x strictly increasing

Try it yourself

Java
class Solution {
    public int findMaxValueOfEquation(int[][] points, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Because xi < xj, the value splits into (yj + xj) + (yi - xi). For each j you only need the maximum y - x in a sliding x-window — a monotonic deque gives it in O(1).
PatternQueue & Monotonic Deque

Instinct Arrival order matters, or you need the max/min of a moving window - reach for a FIFO queue, or a deque of indices kept in sorted order.

Memory hack Old ones leave by the front door, weak ones get bounced out the back - so whoever stands at the front is always the champion.

Open the Queue & Monotonic Deque guide →

Approaches

Brute ForceCheck Every Pair in Range

Time O(n²)Space O(1)

For each right point j, walk left over earlier points while the x-gap stays within k and evaluate the equation directly. Since x is sorted, the walk can stop at the first point that is too far away.

Java
public int findMaxValueOfEquation(int[][] points, int k) {
    int best = Integer.MIN_VALUE;
    for (int j = 1; j < points.length; j++) {
        // x is sorted, so stop once the gap exceeds k
        for (int i = j - 1; i >= 0 && points[j][0] - points[i][0] <= k; i--) {
            int value = points[i][1] + points[j][1] + points[j][0] - points[i][0];
            best = Math.max(best, value);
        }
    }
    return best;
}

Correct and simple, but quadratic when k is large (every pair is in range).

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every Pair in RangeO(n²)O(1)
BetterMax-Heap of (y − x) with Lazy RemovalO(n log n)O(n)
OptimalMonotonic Deque (Sliding Window Maximum)O(n)O(n)
Common pitfalls
  • Reading the answer after pushing point j — pairs it with itself.
  • Forgetting the window check xj - xi ≤ k before using the front.
  • Starting best at 0 — the true maximum can be negative.
Interview tips
  • Drop the absolute value first: sorted x means |xi-xj| = xj-xi.
  • Offer the heap version, then explain why a deque removes the log factor.
  • State the deque invariant: front is the best still-valid partner.
Pattern
Monotonic deque → max/min of a separable term over a sliding window that only moves forward.
My notes saved in this browser