◀ THE GRIND — GREEDY

Longest Turbulent Subarray

MEDIUM✓ CHIP-TIMEDLC #978 — FULL STATEMENT ↗

The drill: Find the longest run of consecutive elements where the comparisons zig-zag — each step must flip between climbing and dropping compared to the step before. A flat or repeated direction ends the run.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

An array of integers arrives, and the goal is measuring the longest contiguous stretch where consecutive comparisons strictly alternate between climbing and dropping — up, then down, then up again, with no two same-direction steps back to back.

A stretch of just one element always counts as turbulent on its own, since there's no comparison yet to break. The moment two consecutive elements are equal, or the direction repeats instead of flipping, that particular run ends there.

Only the length of the longest such alternating stretch is needed, not its starting position or the actual values inside it.

EX 01
arr = [4, 8, 2, 9, 1, 7, 7, 3]
6
RUN BREAKS AT THE REPEATED 7
EX 02
arr = [5, 5, 5, 5]
1
CONSTANT ARRAY, NO DIRECTION EVER CHANGES
EX 03
arr = [1, 2, 3, 4, 5]
2
STRICTLY INCREASING — ONLY ADJACENT PAIRS QUALIFY
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Checking every subarray for the alternating pattern directly re-examines the whole run each time. What could you carry forward from position i to i+1 instead of re-scanning from the start?

HINT 2 THE STRUCTURE

At each position ask only one thing: does this step continue an alternation that the OTHER direction left off, or does it break it? Two small numbers — the best run ending here going up, and the best run ending here going down — are enough to answer that.

HINT 3 ONE STEP FROM THE ANSWER

up[i] = down[i-1] + 1 when arr[i] > arr[i-1] (otherwise reset to 1); down[i] mirrors it for arr[i] < arr[i-1]. An equal pair resets both to 1. The answer is the largest value either counter ever reaches.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE ZIGZAG COUNTERSPATTERN · ALTERNATING RUN DParr = [4, 8, 2, 9, 1, 7, 7, 3]
4
8
2
9
1
7
7
3
UP · DOWN · BEST
up1
down1
best1
STEP 1

Array [4, 8, 2, 9, 1, 7, 7, 3]. up and down both start at 1 — index 0 alone is a turbulent run of length one.

STEP 1 / 9 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/longest-turbulent-subarray.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def maxTurbulenceSize(self, arr: List[int]) -> int:
        up = down = best = 1
        for i in range(1, len(arr)):
            if arr[i] > arr[i - 1]:
                up, down = down + 1, 1
            elif arr[i] < arr[i - 1]:
                down, up = up + 1, 1
            else:
                up = down = 1
            best = max(best, up, down)
        return best
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 12 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED