Two running streaks
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
The code from the episode, ready for LeetCode's Python 3 editor: paste it in and submit.
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.
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