|
| 1 | +package com.thealgorithms.others; |
| 2 | + |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.Deque; |
| 5 | + |
| 6 | +/** |
| 7 | + * Maximum Sliding Window Algorithm |
| 8 | + * |
| 9 | + * This algorithm finds the maximum element in each sliding window of size k |
| 10 | + * in a given array of integers. It uses a deque (double-ended queue) to |
| 11 | + * efficiently keep track of potential maximum values in the current window. |
| 12 | + * |
| 13 | + * Time Complexity: O(n), where n is the number of elements in the input array |
| 14 | + * Space Complexity: O(k), where k is the size of the sliding window |
| 15 | + */ |
| 16 | + |
| 17 | +public class MaximumSlidingWindow { |
| 18 | + |
| 19 | + /** |
| 20 | + * Finds the maximum values in each sliding window of size k. |
| 21 | + * |
| 22 | + * @param nums The input array of integers |
| 23 | + * @param windowSize The size of the sliding window |
| 24 | + * @return An array of integers representing the maximums in each sliding window |
| 25 | + */ |
| 26 | + public int[] maxSlidingWindow(int[] nums, int windowSize){ |
| 27 | + if(nums==null || nums.length==0 || windowSize<=0 || windowSize>nums.length) { |
| 28 | + return new int[0]; // Handle edge cases |
| 29 | + } |
| 30 | + |
| 31 | + int[] result = new int[nums.length - windowSize + 1]; |
| 32 | + Deque<Integer> deque = new ArrayDeque<>(); |
| 33 | + |
| 34 | + for(int currentIndex=0;currentIndex<nums.length;currentIndex++){ |
| 35 | + |
| 36 | + // Remove the first element if it's outside the current window |
| 37 | + if(!deque.isEmpty() && deque.peekFirst()==currentIndex-windowSize) { |
| 38 | + deque.pollFirst(); |
| 39 | + } |
| 40 | + |
| 41 | + // Remove all elements smaller than the current element from the end |
| 42 | + while(!deque.isEmpty() && nums[deque.peekLast()]<nums[currentIndex]) { |
| 43 | + deque.pollLast(); |
| 44 | + } |
| 45 | + |
| 46 | + // Add the current element's index to the deque |
| 47 | + deque.offerLast(currentIndex); |
| 48 | + |
| 49 | + // If we have processed at least k elements, add to result |
| 50 | + if(currentIndex>=windowSize-1) { |
| 51 | + result[currentIndex - windowSize + 1] = nums[deque.peekFirst()]; |
| 52 | + } |
| 53 | + } |
| 54 | + return result; |
| 55 | + } |
| 56 | + public static void main(String[] args) { |
| 57 | + MaximumSlidingWindow msw = new MaximumSlidingWindow(); |
| 58 | + int[] nums = {1,3,-1,-3,5,3,6,7}; |
| 59 | + int k = 3; |
| 60 | + |
| 61 | + // Calculate the maximum sliding window |
| 62 | + int[] result = msw.maxSlidingWindow(nums, k); |
| 63 | + |
| 64 | + // Print the result |
| 65 | + for(int num:result) |
| 66 | + System.out.print(num+" "); |
| 67 | + } |
| 68 | +} |
0 commit comments