Problem Description
Given an integer array nums and an integer threshold, find any contiguous subarray (of length k) such that every element in the subarray is greater than threshold/k. In other words, if m is the minimum element in the subarray then we require m > threshold/k. Return the size k of any subarray that satisfies the condition or -1 if no valid subarray exists.
Key Insights
- The “hard” part of the problem is that the required condition depends on the subarray’s length: each element must be > threshold/k.
- For any contiguous subarray, the “bottleneck” is its minimum element; if the minimum element m satisfies m > threshold/k then all other elements (which are ≥ m) will also satisfy it.
- Instead of checking every possible subarray length (which would be too slow), we compute for each element the maximum contiguous block in which it is the minimum. This uses a “monotonic stack” approach, similar to the largest rectangle in histogram problem.
- For a candidate element with value m that is the minimum over a contiguous subarray of maximum length L, note that any subarray containing that element and contained in that block will have minimum at least m.
- The subarray’s requirement m > threshold/k can be rearranged as k > threshold/m. Thus the smallest valid window length using m as the minimum is k_min = floor(threshold/m) + 1.
- If L (the maximum window length for which m remains the minimum) is at least k_min, then we can form a valid subarray of length k_min.
Space and Time Complexity
Time Complexity: O(n) – Each element is processed a constant number of times using the monotonic stack. Space Complexity: O(n) – For storing the left and right boundaries (and the stack).
Solution
The solution uses a monotonic stack to precompute for every index the number of contiguous elements to the left and right (including the index itself) that are greater than or equal to nums[i]. This gives the maximum subarray length where nums[i] is the minimum element. Then, for each element with value m = nums[i], we calculate the smallest possible subarray length where m can be the minimum and the condition would hold; that is k_min = floor(threshold/m) + 1. If the maximum subarray length L (centered at i) is at least k_min, then such a subarray exists and k_min is a valid answer.