2765. Longest Alternating Subarray
Description
You are given a 0-indexed integer array nums
. A subarray s
of length m
is called alternating if:
m
is greater than1
.s1 = s0 + 1
.- The 0-indexed subarray
s
looks like[s0, s1, s0, s1,...,s(m-1) % 2]
. In other words,s1 - s0 = 1
,s2 - s1 = -1
,s3 - s2 = 1
,s4 - s3 = -1
, and so on up tos[m - 1] - s[m - 2] = (-1)m
.
Return the maximum length of all alternating subarrays present in nums
or -1
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 [2, 3]
, [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:
2 <= nums.length <= 100
1 <= nums[i] <= 104
Solutions
Solution 1: Enumeration
We can enumerate the left endpoint $i$ of the subarray, and for each $i$, we need to find the longest subarray that satisfies the condition. We can start traversing to the right from $i$, and each time we encounter adjacent elements whose difference does not satisfy the alternating condition, we find a subarray that satisfies the condition. We can use a variable $k$ to record whether the difference of the current element should be $1$ or $-1$. If the difference of the current element should be $-k$, then we take the opposite of $k$. When we find a subarray $nums[i..j]$ that satisfies the condition, we update the answer to $\max(ans, j - i + 1)$.
The time complexity is $O(n^2)$, where $n$ is the length of the array. We need to enumerate the left endpoint $i$ of the subarray, and for each $i$, we need $O(n)$ time to find the longest subarray that satisfies the condition. The space complexity is $O(1)$.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|