795. Number of Subarrays with Bounded Maximum
2021/6/18 6:03:02
本文主要是介绍795. Number of Subarrays with Bounded Maximum,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
We are given an array nums
of positive integers, and two positive integers left
and right
(left <= right
).
Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least left
and at most right
.
Example: Input: nums = [2, 1, 4, 3] left = 2 right = 3 Output: 3 Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
Note:
left
,right
, andnums[i]
will be an integer in the range[0, 109]
.- The length of
nums
will be in the range of[1, 50000]
.
class Solution { public int numSubarrayBoundedMax(int[] n, int l, int r) { int j = 0, res = 0, count = 0; for(int i = 0; i < n.length; i++) { if(n[i] >= l && n[i] <= r) { res += i - j + 1; count = i - j + 1; } else if(n[i] < l) res += count; else { j = i + 1; count = 0; } } return res; } }
2 pointers, j是合格subarray的起始点,count是目前为止的合格的subarray的长度,如果当前数字合格,就更新count和res。
如果数字小于l,说明这个数不合格,但是前面的subarray仍然有可能合格,加上count。
如果数字大于r,说明都用不了,重置j和count。
这篇关于795. Number of Subarrays with Bounded Maximum的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南