LeetCode //C - 795. Number of Subarrays with Bounded Maximum

795. Number of Subarrays with Bounded Maximum

Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].

The test cases are generated so that the answer will fit in a 32-bit integer.
 

Example 1:

Input: nums = [2,1,4,3], left = 2, right = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].

Example 2:

Input: nums = [2,9,2,5,6], left = 2, right = 8
Output: 7

Constraints:
  • 1 < = n u m s . l e n g t h < = 1 0 5 1 <= nums.length <= 10^5 1<=nums.length<=105
  • 0 < = n u m s [ i ] < = 1 0 9 0 <= nums[i] <= 10^9 0<=nums[i]<=109
  • 0 < = l e f t < = r i g h t < = 1 0 9 0 <= left <= right <= 10^9 0<=left<=right<=109

From: LeetCode
Link: 795. Number of Subarrays with Bounded Maximum


Solution:

Ideas:
  • start tracks the last index where nums[i] > right, which invalidates any subarray containing it.

  • prevCount holds the number of valid subarrays ending at the previous index — it’s used to accumulate results.

  • The idea is:

    • When nums[i] is within [left, right], all subarrays ending at i and starting after start are valid.
    • When nums[i] < left, we can reuse previous valid subarrays.
    • When nums[i] > right, we reset since any subarray containing it is invalid.
Code:
int numSubarrayBoundedMax(int* nums, int numsSize, int left, int right) {
    int count = 0;
    int prevCount = 0;  // Number of valid subarrays ending at previous index
    int start = -1;     // Start of the most recent segment where nums[i] > right

    for (int i = 0; i < numsSize; i++) {
        if (nums[i] >= left && nums[i] <= right) {
            // Current number is within bounds: extend all subarrays after 'start'
            prevCount = i - start;
            count += prevCount;
        } else if (nums[i] < left) {
            // Can only be added to subarrays that already have a valid max
            count += prevCount;
        } else {
            // nums[i] > right: break the valid segment
            start = i;
            prevCount = 0;
        }
    }
    return count;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值