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

思路:有点动态规划找转移方程的意思

首先,如果所有的数字都在L,R之间,比如序列2,2,2,3 L=2,R=3那么对于第i个数直接加上他前面的数的个数再加1(他自己)就可以了。如果遇到<L的数字比如序列2,2,2,3,1,1相应的序列1,1,11就不能被加上去。但是我们可以加上1和前4个数构成的序列。如果遇到>R的数字,那么此时就重新开始计数。思路很简单,但是实现起来.....

代码中b维护的是<L的数的个数,当遇到满足大于等于L小于等于R的数时清0。a维护的是最后一个满足大于等于L小于等于R的数 和之前的数的个数。(我觉得这是重点,所以多说了几句,但是感觉读者比一定理解,如果你看着比较绕,还是不要看这段了)。

class Solution {
public:
    int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
        int ans = 0;
        int a = 0, b = 0;
        int mark = 0;
        for (auto x : A) {
            if (x <= R && x >= L) {
                a += b;
                b = 0;
                ans += (a+1); 
                ++a;
                mark = 1;
            } else {
                if (x < L) { if (mark) ans += a; ++b;}
                else {
                    a = 0; mark = 0;b = 0;
                }
            }
        }
        return ans;
    }
};
posted on 2018-03-08 18:57  Beserious  阅读(319)  评论(0编辑  收藏  举报