Problem Description
Given an integer array nums of size n, for each subarray size (i + 1) where 0 <= i < n, compute the minimum value in every contiguous subarray of that size. Then, among those minimum values, determine the maximum value. Return an array ans of size n such that ans[i] is the answer for the subarrays of size (i + 1).
Key Insights
- For each element, determine the window in which it is the minimum.
- Use monotonic stacks to compute the previous and next smaller element indices efficiently.
- Each element's contribution can be mapped to a specific subarray size where it acts as the subarray minimum.
- Combine these contributions to build the final answer, then propagate the maximum values for shorter window sizes.
Space and Time Complexity
Time Complexity: O(n) – Each element is pushed and popped from the stack at most once. Space Complexity: O(n) – For the stack and result array.
Solution
To solve the problem, we first compute for each element in nums the farthest distance to the left (previous less element) and to the right (next less element) where the current element is still the minimum. These distances determine the size of the largest subarray in which the element is the minimum.
The steps are as follows:
- Create two arrays, left and right, to store the previous less and next less distance for each element.
- Use a monotonic stack to fill the left array. For each element, pop from the stack until an element smaller than the current element is found.
- Similarly, use a monotonic stack (traversing from right to left) to fill the right array.
- Compute the length of the window for which each element is the minimum as: windowLength = left[i] + right[i] - 1.
- For each computed window size, update an ans array with the maximum element that acts as the minimum for that window size.
- Finally, iterate backward over ans to ensure that for any smaller window size the answer is no smaller than for a larger window that can be achieved.
This algorithm leverages monotonic stacks and contributes each element in one pass, resulting in an optimal solution.