fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <deque>
  4.  
  5. using namespace std;
  6.  
  7. vector<int> maxSlidingWindow(std::vector<int>& nums, int k) {
  8. vector<int> result;
  9. deque<int> window;
  10.  
  11. for (int i = 0; i < nums.size(); ++i) {
  12. if (!window.empty() && window.front() == i - k)
  13. window.pop_front();
  14.  
  15. while (!window.empty() && nums[i] >= nums[window.back()])
  16. window.pop_back();
  17.  
  18. window.push_back(i);
  19.  
  20. if (i >= k - 1)
  21. result.push_back(nums[window.front()]);
  22. }
  23.  
  24. return result;
  25. }
  26.  
  27. int main() {
  28. vector<int> nums = {1, 3, -1, -3, 5, 3, 6, 7};
  29. int k = 3;
  30. vector<int> result = maxSlidingWindow(nums, k);
  31.  
  32. cout << "Maximum sliding window: ";
  33. for (int num : result)
  34. cout << num << " ";
  35. cout << endl;
  36.  
  37. return 0;
  38. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Maximum sliding window: 3 3 5 5 6 7