Input: nums =[1,3,4,3,1], threshold =6Output: 3Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6/3=2.Note that thisis the only valid subarray.
Input: nums =[6,5,6,5,8], threshold =7Output: 1Explanation: The subarray [8] has a size of 1, and 8>7/1=7. So 1is 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.
For each element, we want to find the largest subarray where it is the minimum. For each such subarray, if the minimum element is greater than threshold / length, then that length is a valid answer. We can use a monotonic stack to find the left and right bounds for each element as the minimum.
import java.util.*;
classSolution {
publicintvalidSubarraySize(int[] nums, int threshold) {
int n = nums.length;
int[] left =newint[n], right =newint[n];
Arrays.fill(left, -1);
Arrays.fill(right, n);
Deque<Integer> st =new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
while (!st.isEmpty() && nums[st.peek()]>= nums[i]) {
right[st.pop()]= i;
}
if (!st.isEmpty()) left[i]= st.peek();
st.push(i);
}
for (int i = 0; i < n; ++i) {
int len = right[i]- left[i]- 1;
if (nums[i]> threshold / len) return len;
}
return-1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
funvalidSubarraySize(nums: IntArray, threshold: Int): Int {
val n = nums.size
val left = IntArray(n) { -1 }
val right = IntArray(n) { n }
val st = ArrayDeque<Int>()
for (i in0 until n) {
while (st.isNotEmpty() && nums[st.last()] >= nums[i]) {
right[st.removeLast()] = i
}
if (st.isNotEmpty()) left[i] = st.last()
st.addLast(i)
}
for (i in0 until n) {
val len = right[i] - left[i] - 1if (nums[i] > threshold / len) return len
}
return -1}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
defvalidSubarraySize(nums, threshold):
n = len(nums)
left = [-1] * n
right = [n] * n
st = []
for i in range(n):
while st and nums[st[-1]] >= nums[i]:
right[st.pop()] = i
if st:
left[i] = st[-1]
st.append(i)
for i in range(n):
l = right[i] - left[i] -1if nums[i] > threshold // l:
return l
return-1