Problem
You are given an integer array nums
of size n
. You are asked to solve n
queries for each integer i
in the range 0 <= i < n
.
To solve the ith
query:
- Find the minimum value in each possible subarray of size
i + 1
of the arraynums
. - Find the maximum of those minimum values. This maximum is the answer to the query.
Return a0-indexed integer array ans
of sizen
such thatans[i]
is the answer to theith
query.
A subarray is a contiguous sequence of elements in an array.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
n == nums.length
1 <= n <= 10^5
0 <= nums[i] <= 10^9
Solution
Method 1 – Monotonic Stack for Window Minimums
Intuition
For each window size, the answer is the maximum of all minimums of subarrays of that size. We can use a monotonic stack to efficiently find, for each element, the largest window in which it is the minimum, and then fill the answer array accordingly.
Approach
- For each element, find the index of the previous and next smaller elements using a monotonic stack.
- The length of the window where the current element is the minimum is
right[i] - left[i] - 1
. - For each window size, keep the maximum of the minimums found for that size.
- Fill the answer array from the back to ensure all smaller window sizes are at least as large as the next bigger window size.
- Return the answer array.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— Each element is pushed and popped from the stack at most twice. - 🧺 Space complexity:
O(n)
— For the stacks and answer arrays.