VERY EASY C++ SOLUTION || Single FOR loop || Beginner's Friendly
Intuition\nTo count the number of alternating subarrays within the given array, we iterate through the array, keeping track of the length of alternating subarra
# Intuition\nTo count the number of alternating subarrays within the given array, we iterate through the array, keeping track of the length of alternating subarrays encountered so far. Whenever we encounter a different element compared to the previous one, we increase the length of the alternating subarray. When the element is the same as the previous one, we calculate the number of alternating subarrays that can be formed using the current length of the subarray and add it to the answer. Finally, we return the total count of alternating subarrays.\n\n# Approach\nInitialize variables ans to store the final answer, n to store the size of the input vector, and cnt to keep track of the length of alternating subarrays.\nIterate through the elements of the vector starting from the second element.\nIf the current element is different from the previous one, increment the counter (cnt) to extend the length of the alternating subarray.\nIf the current element is the same as the previous one, calculate the number of alternating subarrays that can be formed using the current length of the subarray and add it to the answer. Reset the counter (cnt) to 1.\nAfter the loop, there might be remaining alternating subarrays that haven\'t been counted. Calculate and add them to the answer.\nReturn the final answer.\n\n# Complexity\n- Time complexity: O(n), where n is the size of the input vector. We traverse the array once.\n- Space complexity: O(1), as we are using only a constant amount of extra space regardless of the input size.\n\n# Code\n```\nclass Solution {\npublic:\n    long long countAlternatingSubarrays(vector<int>& nums) {\n        long long ans = 0;\n        int n = nums.size();\n        int cnt = 1;\n        for (int i = 1; i < n; i++) {\n            if (nums[i] != nums[i - 1]) {\n                cnt++;\n            } else {\n                ans += ((1LL * cnt * (cnt + 1)) / 2);\n                cnt = 1;\n            }\n        }\n        ans += ((1LL * cnt * (cnt + 1)) / 2);\n        return ans;\n    }\n};\n```
['C++']