Number of Subarrays with Bounded Maximum LeetCode solution in Python
1# Runtime: 1574 ms (Top 5.27%) | Memory: 22.4 MB (Top 17.30%)2class Solution:3def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:4n = len(nums)5stack = []6next_greater = [n] * n7prev_greater = [-1] * n8for i in range(n):9while len(stack) > 0 and nums[i] > nums[stack[-1]]:10curr = stack.pop()11next_greater[curr] = i12if len(stack) > 0:13prev_greater[i] = stack[-1]14stack.append(i)15res = 016for i in range(n):17if left <= nums[i] <= right:18l = prev_greater[i]19r = next_greater[i]20res += (i - l) * (r - i)21return res