# LC 2765. Longest Alternating Subarray ### [Problem link](https://leetcode.com/problems/longest-alternating-subarray/) ###### tags: `leedcode` `python` `easy` You are given a **0-indexed** integer array <code>nums</code>. A subarray <code>s</code> of length <code>m</code> is called **alternating** if: - <code>m</code> is greater than <code>1</code>. - <code>s<sub>1</sub> = s<sub>0</sub> + 1</code>. - The **0-indexed** subarray <code>s</code> looks like <code>[s<sub>0</sub>, s<sub>1</sub>, s<sub>0</sub>, s<sub>1</sub>,...,s<sub>(m-1) % 2</sub>]</code>. In other words, <code>s<sub>1</sub> - s<sub>0</sub> = 1</code>, <code>s<sub>2</sub> - s<sub>1</sub> = -1</code>, <code>s<sub>3</sub> - s<sub>2</sub> = 1</code>, <code>s<sub>4</sub> - s<sub>3</sub> = -1</code>, and so on up to <code>s[m - 1] - s[m - 2] = (-1)<sup>m</sup></code>. Return the maximum length of all **alternating** subarrays present in <code>nums</code> or <code>-1</code> if no such subarray exists. A subarray is a contiguous **non-empty** sequence of elements within an array. **Example 1:** ``` Input: nums = [2,3,4,3,4] Output: 4 Explanation: The alternating subarrays are [3,4], [3,4,3], and [3,4,3,4]. The longest of these is [3,4,3,4], which is of length 4. ``` **Example 2:** ``` Input: nums = [4,5,6] Output: 2 Explanation: [4,5] and [5,6] are the only two alternating subarrays. They are both of length 2. ``` **Constraints:** - <code>2 <= nums.length <= 100</code> - <code>1 <= nums[i] <= 10<sup>4</sup></code> ## Solution 1 ```python= class Solution: def alternatingSubarray(self, nums: List[int]) -> int: n = len(nums) res = -1 for i in range(n): for j in range(i + 1, n): if nums[j] - nums[i] != (j - i) % 2: break res = max(res, j - i + 1) return res ``` >### Complexity >n = nums.length >| | Time Complexity | Space Complexity | >| ----------- | --------------- | ---------------- | >| Solution 1 | O($n^2$) | O(1) | ## Note x