Skip to content

Commit 8662254

Browse files
authored
Create count-alternating-subarrays.cpp
1 parent c1bbc1b commit 8662254

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

C++/count-alternating-subarrays.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
// dp
5+
class Solution {
6+
public:
7+
long long countAlternatingSubarrays(vector<int>& nums) {
8+
int64_t result = 0;
9+
for (int i = 0, curr = 0; i < size(nums); ++i) {
10+
if (i - 1 >= 0 && nums[i - 1] == nums[i]) {
11+
curr = 0;
12+
}
13+
result += ++curr;
14+
}
15+
return result;
16+
}
17+
};

0 commit comments

Comments
 (0)