Advertisement
nikunjsoni

1696

Jun 9th, 2021
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int maxResult(vector<int>& nums, int k) {
  4.         int n = nums.size();
  5.         int score = nums[0];
  6.         deque<pair<int, int>> dq;
  7.         dq.push_back({nums[0], 0});
  8.        
  9.         // We just need to have max element in [i-k, i] index range,
  10.         // this can be achieved using monotonic queue which is replacement for priority queue.
  11.         for(int i=1; i<n; i++){
  12.             // Pop indexes less than i-k.
  13.             while(!dq.empty() && dq.front().second < i-k)
  14.                 dq.pop_front();
  15.             score = dq.front().first + nums[i];
  16.            
  17.             // Have monotonically decreasing queue.
  18.             while(!dq.empty() && score >= dq.back().first)
  19.                 dq.pop_back();
  20.             dq.push_back({score, i});
  21.         }
  22.         return score;
  23.     }
  24. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement