2765. Longest Alternating Subarray Easy
1/**
2 * [2765] Longest Alternating Subarray
3 *
4 * You are given a 0-indexed integer array nums. A subarray s of length m is called alternating if:
5 *
6 * m is greater than 1.
7 * s1 = s0 + 1.
8 * 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 to s[m - 1] - s[m - 2] = (-1)^m.
9 *
10 * Return the maximum length of all alternating subarrays present in nums or -1 if no such subarray exists.
11 * A subarray is a contiguous non-empty sequence of elements within an array.
12 *
13 * <strong class="example">Example 1:
14 * <div class="example-block">
15 * Input: <span class="example-io">nums = [2,3,4,3,4]</span>
16 * Output: <span class="example-io">4</span>
17 * Explanation:
18 * 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.
19 * </div>
20 * <strong class="example">Example 2:
21 * <div class="example-block">
22 * Input: <span class="example-io">nums = [4,5,6]</span>
23 * Output: <span class="example-io">2</span>
24 * Explanation:
25 * [4,5] and [5,6] are the only two alternating subarrays. They are both of length 2.
26 * </div>
27 *
28 * Constraints:
29 *
30 * 2 <= nums.length <= 100
31 * 1 <= nums[i] <= 10^4
32 *
33 */
34pub struct Solution {}
35
36// problem: https://leetcode.com/problems/longest-alternating-subarray/
37// discuss: https://leetcode.com/problems/longest-alternating-subarray/discuss/?currentPage=1&orderBy=most_votes&query=
38
39// submission codes start here
40
41impl Solution {
42 pub fn alternating_subarray(nums: Vec<i32>) -> i32 {
43 0
44 }
45}
46
47// submission codes end
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn test_2765() {
55 }
56}
57
Back
© 2025 bowen.ge All Rights Reserved.