nikunjsoni

1499

Apr 16th, 2021
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int findMaxValueOfEquation(vector<vector<int>>& points, int k) {
  4.         deque<pair<int, int>> q;
  5.         int ans=INT_MIN;
  6.         for(int i=0; i<points.size(); i++){
  7.             int x = points[i][0]; int y = points[i][1];
  8.             // Pop from front until elements are in  x-k range.
  9.             while(!q.empty() && x-k > q.front().second)
  10.                 q.pop_front();
  11.            
  12.             // Update ans.
  13.             if(!q.empty()) ans = max(ans, q.front().first + x + y);
  14.            
  15.             // Maintain monotonic behavior by having highest (y-x) values at back of queue.
  16.             // This monotonic behaviour avoids use of priority queue.
  17.             while(!q.empty() && q.back().first < y-x)
  18.                 q.pop_back();
  19.             q.push_back({y-x, x});
  20.         }
  21.         return ans;
  22.     }
  23. };
Advertisement
Add Comment
Please, Sign In to add comment