LeetCde 1499 满足不等式的最大值

单调队列,维护合法窗口内的当前最大值(队头)及未来可能成为最大值的元素下标。

class Solution {
    public int findMaxValueOfEquation(int[][] p, int k) {
        int n = p.length;
        int res = Integer.MIN_VALUE;
        LinkedList<Integer> q = new LinkedList<>();
        for(int j=0; j < n; j++) {
            //1. 维护窗口合法
            while(!q.isEmpty() && p[j][0] - p[q.peek()][0] > k)
                q.removeFirst();
            //2. 更新答案
            if(!q.isEmpty()) {
                int y = p[q.peek()][1], x = p[q.peek()][0];
                res = Math.max(res, p[j][0] + p[j][1] + y - x);
            }
            //3. 保持队列单调递减的前提下,加入当前元素下标
            while(!q.isEmpty() && p[q.peekLast()][1] - p[q.peekLast()][0] < p[j][1] - p[j][0]) 
                q.removeLast();
            q.offer(j);
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/lixyuan/p/13300800.html