[leetcode]795. Number of Subarrays with Bounded Maximum

[leetcode]795. Number of Subarrays with Bounded Maximum


Analysis

出太阳啦~—— [每天刷题并不难0.0]

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.
在这里插入图片描述

Explanation:

寻找满足条件的子串

Implement

class Solution {
public:
    int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
        int len = A.size();
        int res = 0;
        int tmp = 0;
        int j=0;
        for(int i=0; i<len; i++){
            if(A[i]>=L && A[i]<=R){
                res += i-j+1;
                tmp = i-j+1;
            }
            else if(A[i]<L)
                res += tmp;
            else{
                j = i+1;
                tmp = 0;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/86504631