[LeetCode] Subarray With Elements Greater Than Varying Threshold

2334. Subarray With Elements Greater Than Varying Threshold

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
int validSubarraySize(vector<int>& A, int k) {
int n = A.size();
vector<int> dp(n);
priority_queue<pair<int, int>> q;
for(int i = 0; i < n; i++) q.push({A[i],i});
int ma = 0;
for(int res = 1; res <= n; res++) {
double target = 1.0 * k / res;
while(!q.empty() and q.top().first > target) {
auto [_, idx] = q.top(); q.pop();
dp[idx] += 1;
if(idx and dp[idx-1] and idx + 1 < n and dp[idx+1]) {
int left = dp[idx-1];
int right = dp[idx+1];
int sum = left + right + 1;
dp[idx-left] = dp[idx+right] = dp[idx] = sum;
} else if(idx and dp[idx-1]) {
int left = dp[idx-1];
dp[idx] = dp[idx-left] = left + 1;
} else if(idx + 1 < n and dp[idx+1]) {
int right = dp[idx+1];
dp[idx] = dp[idx + right] = right + 1;
}

ma = max(ma, dp[idx]);
if(ma >= res) return res;
}
if(ma >= res) return res;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/10/PS/LeetCode/subarray-with-elements-greater-than-varying-threshold/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.