Skip to content

Latest commit

 

History

History

2765

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

You are given a 0-indexed integer array nums. A subarray s of length m is called alternating if:

  • m is greater than 1.
  • 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 to s[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 [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

Related Topics:
Array, Enumeration

Similar Questions:

Solution 1. Brute Force

// OJ: https://leetcode.com/problems/longest-alternating-subarray
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(1)
class Solution {
public:
    int alternatingSubarray(vector<int>& A) {
        int N = A.size(), ans = -1;
        for (int i = 0; i + 1 < N; ++i) {
            int a = A[i], b = A[i + 1];
            if (b - a != 1) continue;
            int j = i + 2;
            for (; j < N; ++j) {
                if ((j - i) % 2 == 0 && A[j] != a) break;
                if ((j - i) % 2 == 1 && A[j] != b) break;
            }
            ans = max(ans, j - i);
        }
        return ans;
    }
};

Solution 2.

// OJ: https://leetcode.com/problems/longest-alternating-subarray
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int alternatingSubarray(vector<int>& A) {
        int N = A.size(), ans = -1;
        for (int i = 0; i + 1 < N;) {
            int a = A[i], b = A[i + 1];
            if (b - a != 1) {
                ++i;
                continue;
            }
            int j = i + 2;
            for (; j < N; ++j) {
                if ((j - i) % 2 == 0 && A[j] != a) break;
                if ((j - i) % 2 == 1 && A[j] != b) break;
            }
            ans = max(ans, j - i);
            i = j - 1;
        }
        return ans;
    }
};