DDSA
Advertisement

2765. Longest Alternating Subarray

Time: O(n)
Space: O(1)

Approach

DP; dp[i] = run length if alternating diff holds, else reset to 1.

2765.cs
C#
// Approach: DP; dp[i] = run length if alternating diff holds, else reset to 1.
// Time: O(n) Space: O(1)

public class Solution
{
    public int AlternatingSubarray(int[] nums)
    {
        int ans = 1;
        int dp = 1;

        for (int i = 1; i < nums.Length; ++i)
        {
            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;
    }
}
Advertisement
Was this solution helpful?