fork download
  1. #include <vector>
  2. #include <deque>
  3. #include <iostream>
  4.  
  5. std::vector<int> maxSlidingWindow(std::vector<int>& nums, int k) {
  6. std::vector<int> result;
  7. std::deque<int> dq;
  8.  
  9. if (nums.empty()) return result; // Handle the case when nums is empty
  10.  
  11. for (int i = 0; i < nums.size(); ++i) {
  12. // Remove indices from the front of the deque if they are outside the current window
  13. while (!dq.empty() && dq.front() <= i - k) {
  14. dq.pop_front();
  15. }
  16.  
  17. // Remove indices from the back of the deque if the corresponding elements in nums are smaller than or equal to nums[i]
  18. while (!dq.empty() && nums[dq.back()] <= nums[i]) {
  19. dq.pop_back();
  20. }
  21.  
  22. dq.push_back(i);
  23.  
  24. // Add the maximum element to the result when the window size reaches k
  25. if (i >= k - 1) {
  26. result.push_back(nums[dq.front()]);
  27. }
  28. }
  29.  
  30. return result;
  31. }
  32.  
  33. int main() {
  34. std::vector<int> nums1 = {1,3,-1,-3,5,3,6,7};
  35. int k1 = 3;
  36. std::vector<int> result1 = maxSlidingWindow(nums1, k1);
  37. std::cout << "Output for Example 1: ";
  38. for (int num : result1) {
  39. std::cout << num << " ";
  40. }
  41. std::cout << std::endl;
  42.  
  43. std::vector<int> nums2 = {1};
  44. int k2 = 1;
  45. std::vector<int> result2 = maxSlidingWindow(nums2, k2);
  46. std::cout << "Output for Example 2: ";
  47. for (int num : result2) {
  48. std::cout << num << " ";
  49. }
  50. std::cout << std::endl;
  51.  
  52. return 0;
  53. }
  54.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Output for Example 1: 3 3 5 5 6 7 
Output for Example 2: 1