IRAMIACADEMY Picture it. Then code it.
Problem 3105Easy

Longest Strictly Increasing or Strictly Decreasing Subarray

Array

Two running streaks

solution.py
class Solution:
    def longestMonotonicSubarray(self, nums):
        up_run = 1
        down_run = 1
        best = 1
        for i in range(1, len(nums)):
            if nums[i] > nums[i - 1]:
                up_run += 1
                down_run = 1  # a rise breaks any falling run
            elif nums[i] < nums[i - 1]:
                down_run += 1
                up_run = 1  # a drop breaks any rising run
            else:
                up_run = 1  # equal values break both runs
                down_run = 1
            best = max(best, up_run, down_run)
        return best
Time O(n)Space O(1)

The code from the episode, ready for LeetCode's Python 3 editor: paste it in and submit.

The idea

Six posts on a hillside, 3, 1, 4, 4, 5, 9, look like they hold a five-post climb, but the level step between the two fours breaks it. Two trains on a mountain railway, one that only goes uphill and one that only goes downhill, show why the longest run ending at each value is the run before it plus one or a fresh start, so one left-to-right pass with two counters finds the answer.

Check our socials
Another way: Grow from every start
solution.py
class Solution:
    def longestMonotonicSubarray(self, nums):
        n = len(nums)
        best = 1
        for start in range(n):
            # Grow a strictly increasing run from start
            end = start
            while end + 1 < n and nums[end + 1] > nums[end]:
                end += 1
            best = max(best, end - start + 1)
            # Grow a strictly decreasing run from start
            end = start
            while end + 1 < n and nums[end + 1] < nums[end]:
                end += 1
            best = max(best, end - start + 1)
        return best
Time O(n2)Space O(1)