Ctrl K

Sawtooth Readings

Medium
You are given an array of sensor readings readings. Call a segment (a run of consecutive elements) a sawtooth if its values strictly alternate between going up and going down: each element is either greater or smaller than the previous one, and the direction flips at every step. Equal neighbours break the sawtooth. A single element counts as a sawtooth. Return the length of the longest sawtooth segment.
Example 1
readings=[5, 1, 4, 2, 2, 7, 3, 6] → 4

The segment [5, 1, 4, 2] goes down, up, down, then the repeat 2, 2 breaks it. After that [2, 7, 3, 6] is a sawtooth too. Both have length 4.

Example 2
readings=[1, 2, 3, 4] → 2

The values only rise, so a sawtooth can be no longer than one pair of neighbours.

Example 3
readings=[8] → 1

A single element is already a sawtooth of length 1.

Constraints
  • 1 ≤ readings.length ≤ 4 · 10⁴
  • -10⁹ ≤ readings[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvenly Stepped Stretches MediumLongest Run of Ones With One Fix MediumLongest Shared Run MediumTwo Separate Windows MediumTwo Separate Segments With a Given Sum Medium
loading Python…
Input
readings=[5, 1, 4, 2, 2, 7, 3, 6]
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 153 tests on the server, hidden ones included.