Subarray With Elements Greater Than Varying Threshold Problem
Description
LeetCode Problem 2334.
You are given an integer array nums and an integer threshold.
Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k.
Return the size of any such subarray. If there is no such subarray, return -1.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,3,4,3,1], threshold = 6
Output: 3
Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2.
Note that this is the only valid subarray.
Example 2:
Input: nums = [6,5,6,5,8], threshold = 7
Output: 1
Explanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned.
Note that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5.
Similarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.
Therefore, 2, 3, 4, or 5 may also be returned.
Constraints:
1 <= nums.length <= 10^51 <= nums[i], threshold <= 10^9
Solution
Approach: Sort + Union-Find
A subarray of length k is valid when its minimum element m satisfies m > threshold / k, that is m * k > threshold. So we want a subarray whose minimum is large compared to its length.
Process elements from the largest to the smallest. When we handle nums[i] = v, every element already processed is at least v, so the maximal run of processed elements around i is the longest subarray whose minimum is v. Keep these runs with union-find: mark i as processed and merge it with its processed neighbors, tracking each run's size s. If v > threshold / s (integer division), the run has length s and every element is greater than threshold / s, so return s. If no element works, return -1.
Complexity: Time O(n log n) for sorting plus near-linear union-find, space O(n).
class Solution:
def validSubarraySize(self, nums: List[int], threshold: int) -> int:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
def merge(a, b):
pa, pb = find(a), find(b)
if pa == pb:
return
p[pa] = pb
size[pb] += size[pa]
n = len(nums)
p = list(range(n))
size = [1] * n
arr = sorted(zip(nums, range(n)), reverse=True)
vis = [False] * n
for v, i in arr:
if i and vis[i - 1]:
merge(i, i - 1)
if i < n - 1 and vis[i + 1]:
merge(i, i + 1)
if v > threshold // size[find(i)]:
return size[find(i)]
vis[i] = True
return -1