Last Updated: 29 Sep, 2025

Maximum Freshness in Harvest Windows

Moderate
Asked in company
Gameskraft

Problem statement

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.


Input Format:
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.


Output Format:
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.


Note:
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.