LeetCode795. 区间子数组个数

Github
795. Number of Subarrays with Bounded Maximum

[Medium] We are given an array A of positive integers, and two positive integers L and R (L <= R).

Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least L and at most R.

Example :
Input:
A = [2, 1, 4, 3]
L = 2
R = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].

Note:

  • L, R and A[i] will be an integer in the range [0, 10^9].
  • The length of A will be in the range of [1, 50000].

题目:给定一个元素都是正整数的数组A ,正整数 L 以及 R (L <= R)。求连续、非空且其中最大元素满足大于等于L 小于等于R的子数组个数。

思路:双指针,参考linkcnt表示以A[i]结尾的且满足条件的子数组数组。因此分为三种情况:A[i]落在[L,R]区间内,那么满足条件的子数组个数为i-j+1;如果A[i] < L,那么其子数组个数由上一个状态的cnt决定;如果A[i] > R,那么没有以A[i]结尾的子数组能满足条件。

工程代码下载

class Solution {
public:
    int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
        int n = A.size();
        int res = 0;
        for(int i = 0, j = 0, cnt = 0; i < n; ++i){
            if(L <= A[i] && A[i] <= R){
                cnt = i - j + 1;
            }
            else if(A[i] > R){
                cnt = 0;
                j = i + 1;
            }
            res += cnt;
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值