978. Longest Turbulent Subarray

Given an integer array arr, return the length of a maximum size turbulent subarray of arr.

A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.

More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:

  • For i <= k < j:
    • arr[k] > arr[k + 1] when k is odd, and
    • arr[k] < arr[k + 1] when k is even.
  • Or, for i <= k < j:
    • arr[k] > arr[k + 1] when k is even, and
    • arr[k] < arr[k + 1] when k is odd.

 

Example 1:

Input: arr = [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]

Example 2:

Input: arr = [4,8,12,16]
Output: 2

Example 3:

Input: arr = [100]
Output: 1

 

Constraints:

  • 1 <= arr.length <= 4 * 104
  • 0 <= arr[i] <= 109

Rust Solution

struct Solution;
use std::cmp::Ordering::*;

impl Solution {
    fn max_turbulence_size(a: Vec<i32>) -> i32 {
        let n = a.len();
        let mut res = 1;
        let mut inc = 1;
        let mut dec = 1;
        for i in 1..n {
            match (a[i] - a[i - 1]).cmp(&0) {
                Equal => {
                    inc = 1;
                    dec = 1;
                }
                Less => {
                    inc = dec + 1;
                    dec = 1;
                }
                Greater => {
                    dec = inc + 1;
                    inc = 1;
                }
            }
            res = res.max(inc.max(dec));
        }
        res
    }
}

#[test]
fn test() {
    let a = vec![9, 4, 2, 10, 7, 8, 8, 1, 9];
    let res = 5;
    assert_eq!(Solution::max_turbulence_size(a), res);
    let a = vec![4, 8, 12, 16];
    let res = 2;
    assert_eq!(Solution::max_turbulence_size(a), res);
    let a = vec![100];
    let res = 1;
    assert_eq!(Solution::max_turbulence_size(a), res);
    let a = vec![100, 100, 100];
    let res = 1;
    assert_eq!(Solution::max_turbulence_size(a), res);
}

Having problems with this solution? Click here to submit an issue on github.