You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k.

Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length.

It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k.

Input & Output

Example 1 — Basic Case
$ Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
Output: 4
💡 Note: The first two points satisfy |1 - 2| <= 1. The equation value is 3 + 0 + |1 - 2| = 4.
Example 2 — Multiple Valid Pairs
$ Input: points = [[0,0],[3,0],[9,2]], k = 3
Output: 3
💡 Note: Points [0,0] and [3,0] satisfy |0 - 3| <= 3. The equation value is 0 + 0 + |0 - 3| = 3.
Example 3 — Larger Distance
$ Input: points = [[-17,-15],[-10,3],[2,15]], k = 12
Output: 30
💡 Note: Points [-10,3] and [2,15] satisfy |(-10) - 2| <= 12. The equation value is 3 + 15 + |(-10) - 2| = 30.

Constraints

  • 2 ≤ points.length ≤ 105
  • points[i].length == 2
  • -108 ≤ points[i][0], points[i][1] ≤ 108
  • 0 ≤ k ≤ 2 × 108
  • points[i][0] < points[j][0] for all 1 ≤ i < j ≤ points.length

Visualization

Tap to expand
Max Value of Equation INPUT x y (1,3) (2,0) (5,10) (6,-10) points = [[1,3],[2,0],[5,10],[6,-10]] k = 1 ALGORITHM STEPS 1 Equation Transform yi+yj+|xi-xj| = (yj-xj)+(yi+xi) 2 Use Monotonic Deque Track max (y-x) within k 3 Process Each Point Remove expired, calc max 4 Update Result Keep global maximum Pair Calculations (|xi-xj| <= 1) i=0,j=1: (1,3)-(2,0) 3+0+1=4 i=2,j=3: (5,10)-(6,-10) 10-10+1=1 Other pairs: |xi-xj| > k Max = 4 FINAL RESULT (1,3) (2,0) Optimal pair found! OUTPUT 4 Formula: y1+y2+|x1-x2| 3 + 0 + |1-2| = 4 OK - Verified! Key Insight: Since x[i] < x[j], we have |xi-xj| = xj-xi. Transform: yi+yj+(xj-xi) = (yj+xj) + (yi-xi). Use monotonic deque to track max(yi-xi) for valid i's. This achieves O(n) time complexity! TutorialsPoint - Max Value of Equation | Optimal Solution (Monotonic Deque)
Asked in
Google 28 Amazon 15
31.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen