|
| 1 | +package solutions; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +// [Problem] https://leetcode.com/problems/sliding-window-maximum |
| 6 | +class SlidingWindowMaximum { |
| 7 | + // Sliding window with Deque |
| 8 | + // O(n) time, O(k) space |
| 9 | + public int[] maxSlidingWindow(int[] nums, int k) { |
| 10 | + int n = nums.length; |
| 11 | + int[] max = new int[n - k + 1]; |
| 12 | + Deque<Integer> windowIndices = new ArrayDeque<>(); |
| 13 | + for (int i = 0; i < n; i++) { |
| 14 | + int maxIndex = i - k + 1; |
| 15 | + if (!windowIndices.isEmpty() && windowIndices.peek() < maxIndex) { |
| 16 | + windowIndices.poll(); |
| 17 | + } |
| 18 | + while (!windowIndices.isEmpty() && nums[windowIndices.peekLast()] < nums[i]) { |
| 19 | + windowIndices.pollLast(); |
| 20 | + } |
| 21 | + windowIndices.add(i); |
| 22 | + if (maxIndex >= 0) { |
| 23 | + max[maxIndex] = nums[windowIndices.peek()]; |
| 24 | + } |
| 25 | + } |
| 26 | + return max; |
| 27 | + } |
| 28 | + |
| 29 | + // Test |
| 30 | + public static void main(String[] args) { |
| 31 | + SlidingWindowMaximum solution = new SlidingWindowMaximum(); |
| 32 | + |
| 33 | + int[] input = {1, 3, -1, -3, 5, 3, 6, 7}; |
| 34 | + int[] expectedOutput = {3, 3, 5, 5, 6, 7}; |
| 35 | + int[] actualOutput = solution.maxSlidingWindow(input, 3); |
| 36 | + |
| 37 | + System.out.println("Test passed? " + Arrays.equals(expectedOutput, actualOutput)); |
| 38 | + } |
| 39 | +} |
0 commit comments