funcvalidSubarraySize(nums []int, threshold int)int { n := len(nums) type pair struct{ v, i int } a := make([]pair, n) for i, v := range nums { a[i] = pair{v, i} } sort.Slice(a, func(i, j int)bool { return a[i].v > a[j].v })
fa := make([]int, n+1) for i := range fa { fa[i] = i } sz := make([]int, n+1) var find func(int)int find = func(x int)int { if fa[x] != x { fa[x] = find(fa[x]) } return fa[x] } for _, p := range a { i := p.i j := find(i + 1) fa[i] = j // 合并 i 和 i+1 sz[j] += sz[i] + 1 if p.v > threshold/sz[j] { return sz[j] } } return-1 }
classSolution: defvalidSubarraySize(self, nums: List[int], threshold: int) -> int: n = len(nums) left, st = [-1] * n, [] # left[i] 为左侧小于 nums[i] 的最近元素位置(不存在时为 -1) for i, v inenumerate(nums): while st and nums[st[-1]] >= v: st.pop() if st: left[i] = st[-1] st.append(i)
right, st = [n] * n, [] # right[i] 为右侧小于 nums[i] 的最近元素位置(不存在时为 n) for i inrange(n - 1, -1, -1): while st and nums[st[-1]] >= nums[i]: st.pop() if st: right[i] = st[-1] st.append(i)
for num, l, r inzip(nums, left, right): k = r - l - 1 if num > threshold // k: return k return -1
classSolution { public: intvalidSubarraySize(vector<int> &nums, int threshold){ int n = nums.size(); int left[n]; // left[i] 为左侧小于 nums[i] 的最近元素位置(不存在时为 -1) stack<int> s; for (int i = 0; i < n; ++i) { while (!s.empty() && nums[s.top()] >= nums[i]) s.pop(); left[i] = s.empty() ? -1 : s.top(); s.push(i); }
int right[n]; // right[i] 为右侧小于 nums[i] 的最近元素位置(不存在时为 n) s = stack<int>(); for (int i = n - 1; i >= 0; --i) { while (!s.empty() && nums[s.top()] >= nums[i]) s.pop(); right[i] = s.empty() ? n : s.top(); s.push(i); }
for (int i = 0; i < n; ++i) { int k = right[i] - left[i] - 1; if (nums[i] > threshold / k) return k; } return-1; } };
funcvalidSubarraySize(nums []int, threshold int)int { n := len(nums) left := make([]int, n) // left[i] 为左侧小于 nums[i] 的最近元素位置(不存在时为 -1) st := []int{-1} for i, v := range nums { forlen(st) > 1 && nums[st[len(st)-1]] >= v { st = st[:len(st)-1] } left[i] = st[len(st)-1] st = append(st, i) }
right := make([]int, n) // right[i] 为右侧小于 nums[i] 的最近元素位置(不存在时为 n) st = []int{n} for i := n - 1; i >= 0; i-- { forlen(st) > 1 && nums[st[len(st)-1]] >= nums[i] { st = st[:len(st)-1] } right[i] = st[len(st)-1] st = append(st, i) }
for i, num := range nums { k := right[i] - left[i] - 1 if num > threshold/k { return k } } return-1 }