Maximum of Minimum Values in All Subarrays - Problem
Given an integer array nums of size n, you need to solve n different queries. Each query asks: "What's the maximum possible minimum value among all subarrays of a specific length?"
For the i-th query (where 0 ≤ i < n):
- Consider all possible subarrays of length
i + 1 - Find the minimum value in each subarray
- Return the maximum of all those minimum values
Your task is to return an array ans where ans[i] contains the answer to the i-th query.
Example: If nums = [0,1,2,4] and we want subarrays of length 2:
- Subarray
[0,1]→ minimum =0 - Subarray
[1,2]→ minimum =1 - Subarray
[2,4]→ minimum =2 - Maximum of minimums =
max(0,1,2) = 2
Input & Output
example_1.py — Basic Case
$
Input:
[0,1,2,4]
›
Output:
[4,2,1,0]
💡 Note:
Length 1: subarrays [0],[1],[2],[4] → minimums 0,1,2,4 → max = 4. Length 2: subarrays [0,1],[1,2],[2,4] → minimums 0,1,2 → max = 2. Length 3: subarrays [0,1,2],[1,2,4] → minimums 0,1 → max = 1. Length 4: subarray [0,1,2,4] → minimum 0 → max = 0.
example_2.py — Decreasing Array
$
Input:
[10,20,50,1]
›
Output:
[50,20,10,1]
💡 Note:
Length 1: max(10,20,50,1) = 50. Length 2: subarrays [10,20],[20,50],[50,1] → minimums 10,20,1 → max = 20. Length 3: subarrays [10,20,50],[20,50,1] → minimums 10,1 → max = 10. Length 4: minimum of entire array = 1.
example_3.py — Single Element
$
Input:
[7]
›
Output:
[7]
💡 Note:
Only one subarray [7] of length 1, its minimum is 7, so answer is [7].
Visualization
Tap to expand
Understanding the Visualization
1
Identify Each Mountain's Domain
For each peak, find how far left and right you can look before seeing a shorter mountain
2
Calculate Maximum Influence
Each mountain determines the maximum window size where it could be the shortest
3
Fill the Observatory Log
Record the best shortest mountain for each window size, filling gaps by inheritance
Key Takeaway
🎯 Key Insight: Instead of checking every subarray, determine for each element the maximum subarray length where it could be the minimum value. This transforms an O(n³) problem into an elegant O(n) solution using monotonic stacks!
Time & Space Complexity
Time Complexity
O(n)
Single pass with monotonic stack + single pass to process ranges + single pass to fill gaps
✓ Linear Growth
Space Complexity
O(n)
Stack space for monotonic stack plus arrays for left/right boundaries and results
⚡ Linearithmic Space
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 109
- Follow-up: Can you solve this in O(n) time?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code