class Solution {
public:
int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {
// 贡献法:考虑子数组[l, r] 的个数 = r - l + 1, 然后考虑当 l 固定时,r 能到哪【nums[i] >= left && nums[i] <= right】
// from 灵神:https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum/solutions/1988198/tu-jie-yi-ci-bian-li-jian-ji-xie-fa-pyth-n75l/
int n = nums.size();
int ans = 0;
int l = 0, r = -1;
for(int i = 0;i < n;i ++ )
{
if(nums[i] >= left && nums[i] <= right) r = i; // 当前右端点可行
if(nums[i] > right) l = i + 1, r = -1; // l 直接跳到i + 1
if(r != -1) ans += r - l + 1; // l, r 都满足条件的端点 取值可能
}
return ans;
}
};