22. Max of Min for Every Window Size
β GFG solution to the Max of Min for Every Window Size problem: find maximum of minimum values for all possible window sizes using monotonic stack technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an integer array arr[]. The task is to find the maximum of minimum values for every window size k where 1 β€ k β€ arr.size().
For each window size k, consider all contiguous subarrays of length k, determine the minimum element in each subarray, and then take the maximum among all these minimums.
Return the results as an array, where the element at index i represents the answer for window size i+1.
π Examples
Example 1
Input: arr[] = [10, 20, 30, 50, 10, 70, 30]
Output: [70, 30, 20, 10, 10, 10, 10]
Explanation:
Window size 1: minimums are [10, 20, 30, 50, 10, 70, 30], maximum of minimums is 70.
Window size 2: minimums are [10, 20, 30, 10, 10, 30], maximum of minimums is 30.
Window size 3: minimums are [10, 20, 10, 10, 10], maximum of minimums is 20.
Window size 4-7: minimums are [10, 10, 10, 10], maximum of minimums is 10.Example 2
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$1 \le \text{arr}[i] \le 10^6$
β
My Approach
The optimal approach uses Monotonic Stack to efficiently find the span of each element as a minimum in subarrays:
Single Pass Stack Algorithm
Key Insight:
For each element
arr[i], find the maximum window size where it can be the minimum element.This happens in the range from its previous smaller element to its next smaller element.
Stack Processing:
Use a monotonic stack to process elements in a single pass.
When we encounter a smaller element, it means the current element's span as minimum has ended.
Calculate the window size where the popped element was minimum.
Window Size Calculation:
For element at index
mid, if previous smaller is atprevand next smaller is atnext:Window size =
next - prev - 1Update the maximum value for this window size with
arr[mid].
Fill Missing Windows:
Some window sizes might not have any elements as minimums.
Fill these gaps by propagating values from larger windows to smaller windows.
If window size
ihas no answer, it inherits from window sizei+1.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. Each element is pushed and popped from the stack exactly once, making it a linear time solution.
Expected Auxiliary Space Complexity: O(n), where n is the size of the array. We use additional space for the stack and auxiliary arrays to store results and maximum values for each window size.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated