0%

1499. Max Value of Equation

deque O(n) time O(n) space
先把equation拆成后边(x+y)和前边(x-y)之差,即(xj + yj) - (xi - yi),对于每个(xj + yj)只需要知道前边最小的(xi - yi)即可,又因为有一个限制条件|xi - xj| <= k,说明需要用sliding window,参考239. Sliding Window Maximum用deque维护一个xi - yi的升序,每次先把不符合限制条件|xi - xj| <= k的i从前边剔除,然后计算结果,再插入j并在尾部剔除较大的不符合要求的下标以保持升序
另外要注意如果k过小,有可能没有结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int findMaxValueOfEquation(vector<vector<int>>& points, int k) {
int res = INT_MIN;
deque<int> q;
for (int n = size(points), i = 0; i < n; ++i) {
while (!q.empty() && points[i][0] - points[q.front()][0] > k) {
q.pop_front();
}
if (!q.empty()) {
res = max(res, points[i][0] + points[i][1] - (points[q.front()][0] - points[q.front()][1])); // 注意这道题一定要先计算再push新数,因为i < j
}
while (!q.empty() && points[q.back()][0] - points[q.back()][1] >= points[i][0] - points[i][1]) {
q.pop_back();
}
q.push_back(i);
}
return res;
}
};