【Leetcode】795. Number of Subarrays with Bounded Maximum

题目地址:

https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/

给定一个长 n n n数组 A A A,和一个范围 [ l , r ] [l,r] [l,r],问最大值位于这个范围的子数组的个数。

思路是单调栈。开一个严格单调下降的栈,在pop的时候,就能得到pop出的元素的右边最近的比它大的值的下标,和左边最近的不小于它的下标,这样能求出以其为最大值的子数组的个数。求个总和即可。代码如下:

class Solution {
 public:
  int numSubarrayBoundedMax(vector<int>& a, int l, int r) {
    int res = 0, n = a.size();
    stack<int> stk;
    for (int i = 0; i < n; i++) {
      while (stk.size() && a[stk.top()] < a[i]) {
        int t = stk.top(); stk.pop();
        int lc = t - (stk.empty() ? -1 : stk.top()), rc = i - t;
        if (l <= a[t] && a[t] <= r) res += lc * rc;
      }

      stk.push(i);
    }
    while (stk.size()) {
      int t = stk.top(); stk.pop();
      int lc = t - (stk.empty() ? -1 : stk.top()), rc = n - t;
      if (l <= a[t] && a[t] <= r) res += lc * rc;
    }

    return res;
  }
};

时空复杂度 O ( n ) O(n) O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值