Блог пользователя Honestly

Автор Honestly, история, 11 месяцев назад, По-английски

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.

This is the Leetcode problem 1499 ,does anyone have any idea on how to solve this?.i have been scratching my head about this for the last few minutes ,

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

»
11 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

use priority queue

»
11 месяцев назад, скрыть # |
 
Проголосовать: нравится +4 Проголосовать: не нравится

Here, $$$|x_i - x_j| = x_j - x_i$$$, so you can re-write the expression as $$$(y_i - x_i) + (y_j + x_j)$$$. You can iterate through points, adding values of $$$y_i - x_i$$$ to multiset or priority queue, and removing the ones for which $$$x_j - x_i \gt k$$$. Each time, just update the answer if $$$mx + y_j + x_j$$$ is bigger than the biggest answer so far.

Pseudocode
»
11 месяцев назад, скрыть # |
Rev. 2  
Проголосовать: нравится +5 Проголосовать: не нравится

To maximise yi+yj + |xi-xj|. Since the points are sorted by x-coordinates, we can rewrite this as (yj+xj) + (yi-xi). As we iterate through each point j, our goal is to find the maximum value of (yi-xi) for all previous points i that satisfy the condition xj-xi <= k. A sliding window approach is effective in this case.

AC Code