Problem 247818 · medium · Level 02 Linear Data Structures

Longest Zigzag Stretch

arrays · runs · neighbours

A stretch of nums is a zigzag if the direction between neighbours strictly alternates: up, down, up, ... or down, up, down, ... (equal neighbours break a zigzag). Return the length of the longest contiguous zigzag stretch. Any single element is a zigzag of length 1; return 0 for an empty list.

Examples

Input:  nums = [3, 7, 7, 2, 6, 1, 5, 4, 4, 8]
Output: 6
Explanation: 7 > 2 < 6 > 1 < 5 > 4 is the longest zigzag.

Input:  nums = [3, 6, 11, 19, 30]
Output: 2

Input:  nums = [-6]
Output: 1

Constraints

  • 0 <= len(nums) <= 10**5
  • Target: O(n) time, O(1) extra space.

Goals

  • Track two run lengths that feed into each other
  • Reset on equal neighbours
Starting Python…