Back to Sliding Window
Hard
Sliding Window Maximum
You are given an array of integers `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. Return the max sliding window.
Examples
Input:nums = [1,3,-1,-3,5,3,6,7], k = 3
Output:[3,3,5,5,6,7]
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
Input:nums = [1], k = 1
Output:[1]
There is only one element in the array.
Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^41 <= k <= nums.length
Approach
Iterate through each possible window position (from index `0` to `n - k`). For each window, iterate through the `k` elements within it to find the maximum. Store the maximum in a result array.
Complexity Analysis
Time Complexity
O(n * k)
Space Complexity
O(1)
This approach will result in Time Limit Exceeded (TLE) for large arrays and large window sizes.
Solution.java
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || k <= 0) return new int[0]; int n = nums.length; int[] result = new int[n - k + 1]; for (int i = 0; i <= n - k; i++) { int max = nums[i]; for (int j = 1; j < k; j++) { max = Math.max(max, nums[i + j]); } result[i] = max; } return result; }}