题目描述
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
.
Find 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
.
样例
Example 1:
Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
Output: 4
Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
Example 2:
Input: points = [[0,0],[3,0],[9,2]], k = 3
Output: 3
Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
Constraints:
2 <= points.length <= 10^5
points[i].length == 2
-10^8 <= points[i][0], points[i][1] <= 10^8
0 <= k <= 2 * 10^8
points[i][0] < points[j][0]
for all1 <= i < j <= points.length
xi
form a strictly increasing sequence.
算法
(单调队列) $O(n)$
因为题目保证数据xi < xj
,所以不等式变形为(yi - xi) + xj + yj
,于是就变成了找当前点前面横坐标差值不超过k
的最大的yi - xi
,很明显的单调队列的模型。
单调队列里每个元素存储两个数据,第一个是横坐标xi
,第二个是yi - xi
,队列里维护区间里yi - xi
的最大值。
时间复杂度$O(n)$。
C++ 代码
class Solution {
public:
int findMaxValueOfEquation(vector<vector<int>>& points, int k) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
deque<vector<int>> dq;
int res = INT_MIN;
for (const auto & e : points) {
while (!dq.empty() && e[0] - dq.front()[0] > k) dq.pop_front();
if (!dq.empty()) res = max(res, e[0] + e[1] + dq.front()[1]);
while (!dq.empty() && dq.back()[1] < e[1] - e[0]) dq.pop_back();
dq.push_back(vector<int>{e[0], e[1] - e[0]});
}
return res;
}
};
很坐标是什么意思?打错了吧大佬hhh
感谢提醒,已修正~
嗯嗯,其实下面还有一处也是很坐标,但是现在已经意会了