2023-07-21 Leetcode 1499 满足不等式的最大值

79 阅读1分钟

Problem: 1499. 满足不等式的最大值

思路

首先第一个转化是显然的,转换为左端点的y-x,右端点的y+x,我们可以考虑固定一个端点,然后移动剩余的。 困难在于,当我们遍历完之后,移动到下一个端点时,需要尽可能复用已有的点,英文可能只有部分点超出了范围,因此我们引入了单调队列这样的结构。(优先队列应该也可以)

解题方法

遍历所有的右端点,然后维护左端点的优先队列。

Code


class Solution {
    public int findMaxValueOfEquation(int[][] points, int k) {
        int n = points.length;
        int ans = Integer.MIN_VALUE;
        var q = new ArrayDeque<int[]>(); // 维护单调队列
        for (var p : points) {
            int x = p[0];
            int y = p[1];
            while (!q.isEmpty() && q.peekFirst()[0] < x - k) q.pollFirst();
            if (!q.isEmpty()) ans = Math.max(ans, x + y + q.peekFirst()[1]);
            while (!q.isEmpty() && q.peekLast()[1] <= y - x) q.pollLast();
            q.addLast(new int[]{x, y - x});
        }
        return ans;
    }
}