Problem
You are given an array of integersnums. Return the length of the longest subarray of nums which is either strictly increasing or strictly decreasing.
Examples
Constraints
- 1 <= nums.length <= 50
- 1 <= nums[i] <= 50
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 3105 with 16 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 3105 # by problem number
lcpy gen -s longest_monotonic_subarray # by problem name
nums. Return the length of the longest subarray of nums which is either strictly increasing or strictly decreasing.
Input: nums = [1,4,3,3,2]
Output: 2
Explanation:
The strictly increasing subarrays of nums are [1], [2], [3], [3], [4], and [1,4].
The strictly decreasing subarrays of nums are [1], [2], [3], [3], [4], [3,2], and [4,3].
Hence, we return 2.
Input: nums = [3,3,3,3]
Output: 1
Explanation:
The strictly increasing subarrays of nums are [3], [3], [3], and [3].
The strictly decreasing subarrays of nums are [3], [3], [3], and [3].
Hence, we return 1.
Input: nums = [3,2,1]
Output: 3
Explanation:
The strictly increasing subarrays of nums are [3], [2], and [1].
The strictly decreasing subarrays of nums are [3], [2], [1], [3,2], [2,1], and [3,2,1].
Hence, we return 3.
class Solution:
# Time: O(n)
# Space: O(1)
def longest_monotonic_subarray(self, nums: list[int]) -> int:
best = 1
inc = dec = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
inc += 1
dec = 1
elif nums[i] < nums[i - 1]:
dec += 1
inc = 1
else:
inc = dec = 1
best = max(best, inc, dec)
return best
| Time | Space |
|---|---|
| O(n) | O(1) |