✅ Java || Time O(n) || Space O(1) || Sliding Window || Beginner Friendly Explanation ✅
\n\n# Intuition\nThe problem involves counting the number of alternating subarrays in an array. An alternating subarray is defined as a contiguous subarray wher
![image.png](https://assets.leetcode.com/users/images/566b3286-c4fa-4b58-96bc-edc85286ed43_1711858934.2896192.png)\n\n# Intuition\nThe problem involves counting the number of alternating subarrays in an array. An alternating subarray is defined as a contiguous subarray where all elements are either strictly increasing or strictly decreasing. An initial intuition could be to iterate through the array and check for alternating patterns. However, a more efficient approach can be devised by observing that each element can contribute to multiple alternating subarrays, depending on its position and the elements around it.\n\n# Approach\n1. Initialize variables `count` and `consecutive` to keep track of the total count of alternating subarrays and the length of the current consecutive increasing or decreasing sequence, respectively.\n2. Iterate over the array starting from the second element:\n   - If the current element is different from the previous element, increment `consecutive` by 1 and add it to `count`.\n   - If the current element is the same as the previous element, reset `consecutive` to 1 and add it to `count`.\n3. After iterating through the array, add `consecutive` to `count` to account for the remaining subarrays, if applicable.\n4. Return `count` as the total count of alternating subarrays.\n\n# Complexity\n- Time complexity:\n  - The algorithm traverses the array once, resulting in a time complexity of O(n), where n is the length of the input array `nums`.\n- Space complexity:\n  - The space complexity is O(1) since the algorithm uses only a constant amount of extra space for variables such as `count`, `consecutive`, and `n`.\n\n# Code\n```java\nclass Solution {\n    public long countAlternatingSubarrays(int[] nums) {\n        int n = nums.length;\n        long count = 0; // Total count of alternating subarrays\n        int consecutive = 1; // Length of the current consecutive increasing or decreasing sequence\n        \n        for (int i = 1; i < n; i++) {\n            if (nums[i] != nums[i - 1]) {\n                count += consecutive; // Add consecutive to count\n                consecutive++; // Increment consecutive for the new sequence\n            } else {\n                count += consecutive; // Add consecutive to count\n                consecutive = 1; // Reset consecutive for the new sequence\n            }\n        }\n        \n        count += consecutive; // Add the remaining subarrays if applicable\n        \n        return count; // Return the total count of alternating subarrays\n    }\n}\n```
['Array', 'Greedy', 'Sliding Window', 'Java']