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.


 


Example 1:


Input: nums = [1,3,-1,-3,5,3,6,7], k = 3

Output: [3,3,5,5,6,7]

Explanation: 

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

Example 2:


Input: nums = [1], k = 1

Output: [1]

 

Brute Force : - Problem (Time Limit Exceeded)

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
       
        int n = nums.length;

        // This should be of size (n - k + 1), because we get (n - k + 1) windows
        int[] result = new int[n - k + 1];

        int idx = 0; // Index to fill the result array

        // Loop to move the sliding window
        for (int i = 0; i <= n - k; i++) {

            int maxi = Integer.MIN_VALUE; // Variable to keep track of max in current window

            // Loop through the current window of size k
            for (int j = i; j < i + k; j++) {
                maxi = Math.max(maxi, nums[j]); // Update max if current element is greater
            }

            result[idx++] = maxi; // Store max of current window in result
        }

        return result; // Return the array containing max of each window
    }
}


Optmise Solution using Deque


import java.util.*;

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {

        int n = nums.length;
        if (n == 0 || k == 0) return new int[0];

        int[] result = new int[n - k + 1]; // Result array
        Deque<Integer> q = new LinkedList<>(); // Deque to store indices
        int idx = 0; // Result array index

        for (int i = 0; i < n; i++) {

            // Remove indices from front if they are out of the current window
            while (!q.isEmpty() && q.peek() < i - k + 1) {
                q.poll();
            }

            // Remove indices from back if their corresponding values are less than current element
            while (!q.isEmpty() && nums[q.peekLast()] < nums[i]) {
                q.pollLast();
            }

            // Add current element's index to the deque
            q.offer(i);

            // If we have at least 'k' elements processed, add the front (max) to result
            if (i >= k - 1) {
                result[idx++] = nums[q.peek()];
            }
        }

        return result;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence