74th LeetCode Weekly Contest 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 Land 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],但不能超过R

应该知道了,A[i]在L,R之间是num+=(i-j),超过R需要记录j=i,但如何处理小于L的数字

因为必须存在[L,R],单纯的小于L不能算,那么就拿一个k记录一下不在[L,R]的位置,然后(i-j)-(i-k+1)就好了

复制代码
 1 class Solution {
 2 public:
 3     int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
 4             int aLen=A.size();
 5             int num=0;
 6             int k=0;
 7             int i=0,j=-1;
 8             for(int i=0;i<aLen;i++){
 9                 if(A[i]>R){
10                     k=i+1;
11                     j=i;
12                 }else if(A[i]<L){
13                     num+=(i-j)-(i-k+1);
14                 }else{
15                     num+=(i-j);
16                     k=i+1;
17                 }
18             }
19             return num;
20     }
21 };
复制代码

 

posted @   樱花落舞  阅读(353)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示