输入:nums = [2,1,4,3], left = 2, right = 3 输出:3 解释:满足条件的三个子数组:[2], [2, 1], [3]
示例 2:
1 2
输入:nums = [2,9,2,5,6], left = 2, right = 8 输出:7
提示:
1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= left <= right <= 109
代码:
Python
1 2 3 4 5 6 7 8
classSolution: defnumSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: ans, i0, i1 = 0, -1, -1 for i, x inenumerate(nums): if x > right: i0 = i if x >= left: i1 = i ans += i1 - i0 return ans
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: intnumSubarrayBoundedMax(vector<int>& nums, int left, int right){ int ans = 0, i0 = -1, i1 = -1; for (int i = 0; i < nums.size(); ++i) { int x = nums[i]; if (x > right) i0 = i; if (x >= left) i1 = i; ans += i1 - i0; } return ans; } };