All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2701_2800.s2765_longest_alternating_subarray.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g2701_2800.s2765_longest_alternating_subarray;

// #Easy #Array #Enumeration #2023_09_24_Time_2_ms_(82.60%)_Space_43_MB_(69.16%)

/**
 * 2765 - Longest Alternating Subarray\.
 *
 * Easy
 *
 * 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
**/
@SuppressWarnings("java:S135")
public class Solution {
    public int alternatingSubarray(int[] nums) {
        int result = -1;
        int previous = 0;
        int sum = 1;
        for (int i = 1; i < nums.length; i++) {
            int diff = nums[i] - nums[i - 1];
            if (Math.abs(diff) != 1) {
                sum = 1;
                continue;
            }
            if (diff == previous) {
                sum = 2;
            }
            if (diff != previous) {
                if (diff != (sum % 2 == 0 ? -1 : 1)) {
                    continue;
                }
                sum++;
                previous = diff;
            }
            result = Math.max(result, sum);
        }
        return result;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy