[Leetcode] 795. Number of Subarrays with Bounded Maximum 解题报告

这篇博客详细介绍了LeetCode 795题目的解题报告。作者通过使用双指针技巧,将数组分为三种情况处理,以找出满足最大元素在[L, R]范围内的连续子数组。文章讨论了算法的时间复杂度为O(n),并提供了相应的代码实现。" 109904478,10168791,Java反射与枚举详解,"['Java', '反射', '枚举']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

思路

我们定义[left, right]表示符合条件的合法区间,并且遍历数组A,根据A[right]的大小,可以分为三种情况进行处理:

1)A[right]在[L, R]区间内,所以此时我们拥有从[left, right]...到[right, right]一共(right - left + 1)个合法的区间,所以我们更新res += (right - left + 1),并且更新count的值(后面会有用);2)A[right]小于L,此时虽然A[right]不在[L, R]区间内,但是对于前面的count个合法区间,每个加上A[right],仍然可以形成合法的区间,所以res += count;3)A[right] > R,此时所有包含A[right]的区间都将不再合法,所以我们更新左边界left = right + 1,并更新count = 0。

算法的空间复杂度为O(1),时间复杂度为O(n),应该是最优的空间和时间复杂度了。

代码

class Solution {
public:
    int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
        int left = 0, count = 0, res = 0;
        for (int right = 0; right < A.size(); ++right) {
            if (A[right] >= L && A[right] <= R) {   // A[right] is in the range
                res += (right - left + 1);
                count = (right - left + 1);
            }
            else if (A[right] < L) {                // A[right] is below L, but can be included in the range
                res += count;
            }
            else {                                  // A[right] is above R, so we have to clean the range
                left = right + 1;
                count = 0;
            }
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值