# 795. Number of Subarrays with Bounded Maximum
阿新 • • 發佈:2018-12-01
795. 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 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].
遍歷陣列,將遍歷的元素分為下列三種情況來討論:
①:if(A[i] >= L && A[i] <= R)
在這種情況下,子陣列的種類res += i - j + 1。即每新增一個滿足①條件的點子列的情況就增加 i - j + 1種(j為當前子陣列的開頭,i為當前子陣列的結尾,注意A[j]嚴格滿足A[j] >= L && A[j] <= R)同時記錄此時的子列長度countnums= i - j + 1。
②:
else if(A[i] < L)
此時新加的可能情況為
res = res + countnums;
注意此時的A[i]實際上是比給定的範圍要小的點,是不滿足題意的,但是如果它之前的countnums不為0,說明最近一次的子列加上該點也可以構成新子列,但是必須以countnums中的子列(該子列中的最後一個元素為A[j]嚴格滿足A[j] >= L && A[j] <= R)中的某個元素為開始,以A[i]為結尾)。③
A[i]>R
此時意味著一箇舊子列的結束,更新各個對應的引數
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
int size = A.size();
int countnums = 0;
int res = 0;
int j = 0;
for(int i = 0; i<size; i++)
{
if(A[i] >= L && A[i] <= R)
{
res += i - j + 1;
countnums = i - j + 1;
}
else if(A[i] < L)
{
res = res + countnums;
}
else
{
j = i + 1;
countnums = 0;
if(j > size)
{
break;
}
}
}
return res;
}
};