Skip to content

2765. Longest Alternating Subarray

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int alternatingSubarray(vector<int>& nums) {
    int ans = 1;
    int dp = 1;

    for (int i = 1; i < nums.size(); ++i) {
      const int targetDiff = dp % 2 == 0 ? -1 : 1;
      // Append nums[i] to the current alternating subarray.
      if (nums[i] - nums[i - 1] == targetDiff)
        ++dp;
      // Reset the alternating subarray to nums[i - 1..i].
      else if (nums[i] - nums[i - 1] == 1)
        dp = 2;
      // Reset the alternating subarray to nums[i].
      else
        dp = 1;
      ans = max(ans, dp);
    }

    return ans == 1 ? -1 : ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int alternatingSubarray(int[] nums) {
    int ans = 1;
    int dp = 1;

    for (int i = 1; i < nums.length; ++i) {
      final int targetDiff = dp % 2 == 0 ? -1 : 1;
      // Append nums[i] to the current alternating subarray.
      if (nums[i] - nums[i - 1] == targetDiff)
        ++dp;
      // Reset the alternating subarray to nums[i - 1..i].
      else if (nums[i] - nums[i - 1] == 1)
        dp = 2;
      // Reset the alternating subarray to nums[i].
      else
        dp = 1;
      ans = Math.max(ans, dp);
    }

    return ans == 1 ? -1 : ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def alternatingSubarray(self, nums: list[int]) -> int:
    ans = 1
    dp = 1

    for i in range(1, len(nums)):
      targetDiff = -1 if dp % 2 == 0 else 1
      # Append nums[i] to the current alternating subarray.
      if nums[i] - nums[i - 1] == targetDiff:
        dp += 1
      # Reset the alternating subarray to nums[i - 1..i].
      elif nums[i] - nums[i - 1] == 1:
        dp = 2
      # Reset the alternating subarray to nums[i].
      else:
        dp = 1
      ans = max(ans, dp)

    return -1 if ans == 1 else ans