标签:count 795 right nums int Subarrays Bounded subarray left
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。
标签:count,795,right,nums,int,Subarrays,Bounded,subarray,left 来源: https://www.cnblogs.com/wentiliangkaihua/p/14898003.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。