Number of Subarrays with Bounded Maximum(区间子数组个数)

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].

1.题目大意

给定边界值L和R,求解连续子数组的最大值在区间[L,R]范围的个数

2.分析

解决本题的关键地方在于:

根据数组中大于R的元素作为分界划分合理的区间,要考虑重复计算的问题。例如:

L=2, R=3  A=[2,2,1,3,4,3]  可以将其分为 [2,2,1,3] 和 [3],要将不满足条件的子数组去掉。

比较简单的解法:两层循环,第一层循环表示子数组的起点,第二层循环表示添加到子数组的元素,依次往后遍历,如果碰到大于R的元素,则说明添加后面的元素无法满足题目要求。时间复杂度为O(n^2)

下面主要针对关键问题①来进行求解,如果我们仔细去看,可以发现,其实根据大于R的元素去划分区间是比较合理的,难点就在于解决重复的问题。对于n个元素的数组,则有(n+1) * n / 2个子数组;这些子数组包含其中的最大值元素不在[L,R]范围内的数据,所以要将其去除,我们只需去掉最大值小于L的子数组即可。

综上,首先根据大于R的元素进行划分数组;统计数组的所有子数组个数,然后减去最大值小于L的子数组,剩下的即为最大值在[L,R]区间的子数组。例如 [2,1,4,3]    L=2  R=3

划分成两个数组 [2,1] 和 [3]

统计[2,1]满足条件的子数组:[2] [2,1] [1] - [1] = [2] [2,1] 共2种

故总共 3 种子数组满足条件

class Solution {
public:
    int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
        return getLessBoundNum(A, R) - getLessBoundNum(A, L - 1);
    }

    int getLessBoundNum(const vector<int>& A, const int bound) {
        int res = 0, cur = 0;
        for (int pos = 0; pos < A.size(); ++pos) {
            cur = A[pos] <= bound ? cur + 1 : 0;
            res += cur;
        }

        return res;
    }
};

[1]https://www.cnblogs.com/grandyang/p/9237967.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值