
You have a row of fruit baskets represented by an array freshness, where each element is the freshness score of the fruit in that basket. You are also given a basket cart size k.
You will slide this cart of size k along the row of baskets, one basket at a time, from left to right. For each position of the cart (each "window" of k baskets), you need to determine the maximum freshness score within that window.
Your task is to return a list of the maximum freshness scores for each k-sized window.
The first line of input contains two space-separated integers, 'N' and 'K'.
The second line contains 'N' space-separated integers, representing the freshness array.
Print a single line containing N-K+1 space-separated integers, where each integer is the maximum value for each consecutive window of size K.
A naive solution of iterating through each of the N-K+1 windows and finding the maximum in each would be O(N * K), which is too slow for the given constraints.
The optimal solution uses a sliding window approach with a Deque (Double-Ended Queue). The deque is used to store indices of elements in the current window, maintained in decreasing order of their freshness scores. This allows finding the maximum for each window in O(1) amortized time, leading to an overall O(N) solution.
8 3
1 3 -1 -3 5 3 6 7
3 3 5 5 6 7
- Window 1: `[1, 3, -1]`, max is 3.
- Window 2: `[3, -1, -3]`, max is 3.
- Window 3: `[-1, -3, 5]`, max is 5.
- Window 4: `[-3, 5, 3]`, max is 5.
- Window 5: `[5, 3, 6]`, max is 6.
- Window 6: `[3, 6, 7]`, max is 7.
5 1
10 20 30 40 50
10 20 30 40 50
When the window size is 1, the maximum of each window is simply the element itself.
The expected time complexity is O(N).
1 <= K <= N <= 10^5
-10^9 <= freshness[i] <= 10^9
Time limit: 1 sec