forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
48 lines (37 loc) · 1.01 KB
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/// Source : https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/
/// Author : liuyubobobo
/// Time : 2018-03-05
#include <iostream>
#include <vector>
using namespace std;
/// Counting
/// Using function count to calculate the subarray numbers of maximum <= bound
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
return count(A, R) - count(A, L - 1);
}
private:
int count(const vector<int>& nums, int bound){
int res = 0;
int cur = 0;
for(int num: nums)
if(num <= bound){
cur ++;
res += cur;
}
else
cur = 0;
return res;
}
};
int main() {
// vector<int> A1 = {2, 1, 4, 3};
// cout << Solution().numSubarrayBoundedMax(A1, 2, 3) << endl;
vector<int> A2 = {2, 9, 2, 5, 6};
cout << Solution().numSubarrayBoundedMax(A2, 2, 8) << endl;
return 0;
}