Sliding Window Maximum

Source: Internet
Author: User

Given an array nums, there is a sliding window of size K which are moving from the very left of the array To the very right. You can only see the K numbers in the window. Each of the sliding window moves right by one position.

For example,
Given nums = [1,3,-1,-3,5,3,6,7] , and k = 3.

Window position                Max---------------               -----[1  3  -1]-3  5  3  6  7       3 1 [3  - 1  -3] 5  3  6  7       3 1 3  [-1  -3  5] 3  6  7       5 1  3  -1 [-3  5  3] 6  7       5 1  3  -1  -3 [5  3  6] 7       6 1  3  -1  -3  5 [3  6  7]      7

Therefore, return the max sliding window as [3,3,5,5,6,7] .

Note:
You may assume K are always valid, Ie:1≤k≤input array's size for non-empty array.

Follow up:
Could solve it in linear time?

Analyse:find the maximum in each window and push it into the result vector.

Runtime:340ms.

1 classSolution {2  Public:3vector<int> Maxslidingwindow (vector<int>& Nums,intk) {4vector<int>result;5         if(nums.size () = =0)returnresult;6         7         intleft =0, right = K-1;8          while(Right <nums.size ()) {9             inttemp = int_min;//maximum in the current windowTen             if(left = right) temp =Nums[left]; One             Else{ A                  for(inti = left; I <= right; i++) -temp =Max (temp, nums[i]); -             } the Result.push_back (temp); -left++; -right++; -         } +         returnresult; -     } +};

Sliding Window Maximum

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.