# Leetcode-239-Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time 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 is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

 public class Solution
{
public int[] MaxSlidingWindow(int[] nums, int k)
{
if (nums.Length == 0)
return new int[]{};
if (k == 1)
return nums;
int[] ret = new int[nums.Length - k + 1];
ret[0] = help(nums, k, 0);
for (int i = k; i < nums.Length; i++)
{
if (ret[i - k] <= nums[i])
ret[i - k + 1] = nums[i];
else
ret[i - k + 1] = help(nums, k, i - k + 1);
}
return ret;
}
public int help(int[] nums, int k, int begin)
{
int max = nums[begin];
for (int i = begin; i <= begin + k - 1; i++)
{
max = max >= nums[i] ? max : nums[i];
}
return max;
}
}

 public class Solution
{
public int[] MaxSlidingWindow(int[] nums, int k)
{
if (k == 0) return new int[0];
int[] res = new int[nums.Length - k + 1];//存储结果
for (int i = 0; i < nums.Length; i++)
{
//元素的索引 i 入队之前，将比nums[i]小的所有元素的索引在队列中删除，这样可以保证队列中的元素索引所指的数组对应元素是按照降序排列。
while (q.Count != 0 && nums[i] >= nums[q.Last()])
{
q.RemoveLast();
}
//当前索引 i 与队列中第一个索引的差如果大于k，说明当前队列里的元素个数超过窗口大小，需要删除元素，因为索引是顺序入队的，所以第一个元素就是要删除的元素。
if (i - q.First() + 1 > k)

{
q.RemoveFirst();
}
//在 i -k +1 =0 开始对res赋值。
if (i + 1 >= k) res[i - k + 1] = nums[q.First()];
}
return res;
}
}

#### LeetCode 239. Sliding Window Maximum（滑动窗口最大值）

2016-04-06 12:53:10

#### leetcode 239: Sliding Window Maximum

2015-07-19 15:41:45

#### [LeetCode]239.Sliding Window Maximum

2015-07-19 15:49:54

#### leetcode 239. Sliding Window Maximum 双端队列 滑动窗口最大值

2017-09-04 15:25:15

#### LeetCode -- Sliding Window Maximum

2015-11-11 00:33:31

#### Windows下用Nginx+Tomcat配置集群负载均衡

2015-01-27 15:01:01

#### LeetCode题解——Sliding Window Maximum

2015-09-16 17:28:34

#### LeetCode 239. Sliding Window Maximum 题解(下)

2017-10-15 18:32:43

#### 239. Sliding Window Maximum 固定的滑动窗口里找最大值

2016-09-01 17:47:03

#### nginx 实现Web应用程序的负载均衡

2015-04-13 22:17:10