Max Value of Equation (LeetCode 1499): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Keep a deque of
(yi - xi, xi)pairs in decreasing order ofyi - xi, and setresultto negative infinity. - For each point
(xj, yj), pop from the front whilexj - dq[0][1] > k, removing points that are too far left. - If the deque is not empty, update
resultwithyj + xj + dq[0][0], the best partner for this point. - Pop from the back while the last value is at most
yj - xj, since the new point dominates it. - Append
(yj - xj, xj)to the back. - Return
resultafter processing every point.
Step-by-step example
points = [[1,3], [2,0], [5,10], [6,-10]], k = 1
- Point (1,3): the deque is empty, so there is no pair yet. Push (3 - 1, 1) = (2, 1).
- 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). - 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).
- Point (6,-10): the front (5, 5) is within range, candidate -10 + 6 + 5 = 1, which does not beat 4. Push (-16, 6).
- 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 result1class Solution {
2 public int findMaxValueOfEquation(int[][] points, int k) {
3 Deque<int[]> dq = new ArrayDeque<>();
4 int result = Integer.MIN_VALUE;
5
6 for (int[] p : points) {
7 int xj = p[0], yj = p[1];
8
9 while (!dq.isEmpty() && xj - dq.peekFirst()[1] > k) {
10 dq.pollFirst();
11 }
12
13 if (!dq.isEmpty()) {
14 result = Math.max(result, yj + xj + dq.peekFirst()[0]);
15 }
16
17 while (!dq.isEmpty() && dq.peekLast()[0] <= yj - xj) {
18 dq.pollLast();
19 }
20 dq.offerLast(new int[]{yj - xj, xj});
21 }
22
23 return result;
24 }
25}1class Solution {
2public:
3 int findMaxValueOfEquation(vector<vector<int>>& points, int k) {
4 deque<pair<int, int>> dq; // {yi - xi, xi}
5 int result = INT_MIN;
6
7 for (auto& p : points) {
8 int xj = p[0], yj = p[1];
9
10 while (!dq.empty() && xj - dq.front().second > k) {
11 dq.pop_front();
12 }
13
14 if (!dq.empty()) {
15 result = max(result, yj + xj + dq.front().first);
16 }
17
18 while (!dq.empty() && dq.back().first <= yj - xj) {
19 dq.pop_back();
20 }
21 dq.push_back({yj - xj, xj});
22 }
23
24 return result;
25 }
26};Time and space complexity
O(n)
Each point is appended once and removed at most once from either end of the deque, so the total work is linear.
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 + xiinstead ofyi - xiin the deque, which gets the sign of the distance term wrong. - Initializing
resultto 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.