fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <deque>
  4.  
  5. std::vector<int> maxSlidingWindow(std::vector<int>& nums, int k) {
  6. std::vector<int> result;
  7. std::deque<int> window;
  8.  
  9. for (int i = 0; i < nums.size(); ++i) {
  10. // Remove elements outside of the window
  11. if (!window.empty() && window.front() == i - k)
  12. window.pop_front();
  13.  
  14. // Remove elements smaller than the current number
  15. while (!window.empty() && nums[i] >= nums[window.back()])
  16. window.pop_back();
  17.  
  18. // Add current number to the window
  19. window.push_back(i);
  20.  
  21. // If the window is at least of size k, add the maximum element to the result
  22. if (i >= k - 1)
  23. result.push_back(nums[window.front()]);
  24. }
  25.  
  26. return result;
  27. }
  28.  
  29. int main() {
  30. std::vector<int> nums = {1, 3, -1, -3, 5, 3, 6, 7};
  31. int k = 3;
  32. std::vector<int> result = maxSlidingWindow(nums, k);
  33.  
  34. std::cout << "Maximum sliding window: ";
  35. for (int num : result)
  36. std::cout << num << " ";
  37. std::cout << std::endl;
  38.  
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
Maximum sliding window: 3 3 5 5 6 7