Untitled

 avatar
unknown
plain_text
a month ago
1.4 kB
1
Indexable
import java.util.*;

public class SlidingWindowMinimum {
    public int[] minSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        int[] result = new int[n - k + 1];
        Deque<Integer> deque = new LinkedList<>();
        int i = 0, j = 0, idx = 0;

        // Process the first k elements
        while (j < k) {
            // Remove larger elements as they are not useful
            while (!deque.isEmpty() && nums[deque.peekLast()] >= nums[j]) {
                deque.pollLast();
            }
            deque.addLast(j);
            j++;
        }
        // Store the minimum for the first window
        result[idx++] = nums[deque.peekFirst()];

        // Process the rest of the elements
        while (j < n) {
            // Remove larger elements as they are not useful
            while (!deque.isEmpty() && nums[deque.peekLast()] >= nums[j]) {
                deque.pollLast();
            }
            deque.addLast(j);

            i++;
            // Remove elements not in the current window
            if (!deque.isEmpty() && deque.peekFirst() < i) {
                deque.pollFirst();
            }

            // Store the minimum for the current window
            result[idx++] = nums[deque.peekFirst()];
            j++;
        }

        return result;
    }
}
Leave a Comment