Input: nums =[1,3,5,4,4,6]Output: 10Explanation: The strictly increasing subarrays are the following:- Subarrays of length 1:[1],[3],[5],[4],[4],[6].- Subarrays of length 2:[1,3],[3,5],[4,6].- Subarrays of length 3:[1,3,5].The total number of subarrays is6+3+1=10.
Example 2:
1
2
3
Input: nums =[1,2,3,4,5]Output: 15Explanation: Every subarray is strictly increasing. There are 15 possible subarrays that we can take.
A strictly increasing subarray can be counted by tracking the length of the current increasing segment. For each element, if it is greater than the previous, extend the segment; otherwise, reset. The number of strictly increasing subarrays ending at each position is equal to the length of the current segment.
classSolution {
public:longlong countSubarrays(vector<int>& nums) {
longlong ans =0, len =1;
for (int i =0; i < nums.size(); ++i) {
if (i ==0|| nums[i] <= nums[i-1]) len =1;
else len++;
ans += len;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funccountSubarrays(nums []int) int64 {
ans, l:= int64(0), 1fori:=0; i < len(nums); i++ {
ifi==0||nums[i] <=nums[i-1] {
l = 1 } else {
l++ }
ans+= int64(l)
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publiclongcountSubarrays(int[] nums) {
long ans = 0;
int len = 1;
for (int i = 0; i < nums.length; i++) {
if (i == 0 || nums[i]<= nums[i-1]) len = 1;
else len++;
ans += len;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funcountSubarrays(nums: IntArray): Long {
var ans = 0Lvar len = 1for (i in nums.indices) {
if (i ==0|| nums[i] <= nums[i-1]) len = 1else len++ ans += len
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defcountSubarrays(self, nums: list[int]) -> int:
ans =0 l =1for i in range(len(nums)):
if i ==0or nums[i] <= nums[i-1]:
l =1else:
l +=1 ans += l
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfncount_subarrays(nums: Vec<i32>) -> i64 {
letmut ans =0i64;
letmut len =1i64;
for i in0..nums.len() {
if i ==0|| nums[i] <= nums[i-1] {
len =1;
} else {
len +=1;
}
ans += len;
}
ans
}
}