26. Maximum of Minimum for Every Window Size
The problem can be found at the following link: Question Link
Problem Description
Given an array of integers arr[], find the maximum of the minimum element for every window size w from 1 to N.
Examples
Example 1
Input:
arr[] = {10, 20, 30, 50, 10, 70, 30}Output:
70 30 20 10 10 10 10Explanation:
Window Size (k)
Subarrays of size k
Minimum in each subarray
Maximum among these minimums
1
{10}, {20}, {30}, {50}, {10}, {70}, {30}
10, 20, 30, 50, 10, 70, 30
70
2
{10, 20}, {20, 30}, {30, 50}, {50, 10}, {10, 70}, {70, 30}
10, 20, 30, 10, 10, 30
30
3
{10, 20, 30}, {20, 30, 50}, {30, 50, 10}, {50, 10, 70}, {10, 70, 30}
10, 20, 10, 10, 10
20
4
{10, 20, 30, 50}, {20, 30, 50, 10}, {30, 50, 10, 70}, {50, 10, 70, 30}
10, 10, 10, 10
10
5
{10, 20, 30, 50, 10}, {20, 30, 50, 10, 70}, {30, 50, 10, 70, 30}
10, 10, 10
10
6
{10, 20, 30, 50, 10, 70}, {20, 30, 50, 10, 70, 30}
10, 10
10
7
{10, 20, 30, 50, 10, 70, 30}
10
10
Example 2
Input:
Output:
Explanation:
Window Size (k)
Subarrays of size k
Minimum in each subarray
Maximum among these minimums
1
{1}, {3}, {2}, {4}, {5}
1, 3, 2, 4, 5
5
2
{1, 3}, {3, 2}, {2, 4}, {4, 5}
1, 2, 2, 4
3
3
{1, 3, 2}, {3, 2, 4}, {2, 4, 5}
1, 2, 2
2
4
{1, 3, 2, 4}, {3, 2, 4, 5}
1, 2
1
5
{1, 3, 2, 4, 5}
1
1
Constraints:
$( 1 \leq N \leq 10^5 )$
$( 1 \leq arr[i] \leq 10^6 )$
My Approach
Optimized Stack-Based Approach (O(N) Time, O(N) Space)
To efficiently find the maximum of the minimum for every window size, we use a monotonic stack to determine the window size for which each element is the minimum.
Algorithm Steps:
Find the nearest smaller elements on both left and right sides
Store the left boundary (
prevSmaller[i]) wherearr[i]is the minimum.Store the right boundary (
nextSmaller[i]) wherearr[i]is the minimum.Use stacks to efficiently compute these values.
Calculate the window size where each element is the minimum
The window size for
arr[i]isnextSmaller[i] - prevSmaller[i] - 1.
Store maximum values for each window size
Use an array
res[]to store the maximum of the minimums for each window size.
Propagate the maximum values
Ensure
res[i]contains the maximum for all larger windows using backward propagation.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(N), since each element is processed once.
Expected Auxiliary Space Complexity: O(N), for storing index boundaries and stack operations.
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