Created
February 3, 2025 17:37
-
-
Save tatsuyax25/967ba881ed6936ebab6a02db5fb2f511 to your computer and use it in GitHub Desktop.
You are given an array of integers nums. Return the length of the longest subarray of nums which is either strictly increasing or strictly decreasing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @return {number} | |
*/ | |
var longestMonotonicSubarray = function(nums) { | |
if (nums.length === 0) return 0; | |
let maxLength = 1; | |
let currentLength = 1; | |
let increasing = null; | |
for (let i = 1; i < nums.length; i++) { | |
if (nums[i] > nums[i - 1]) { | |
// If the subarray is strictly increasing | |
if (increasing !== true) { | |
increasing = true; | |
currentLength = 2; // Reset current length for new subarray | |
} else { | |
currentLength++; | |
} | |
} else if (nums[i] < nums[i - 1]) { | |
// If the subarray is strictly decreasing | |
if (increasing !== false) { | |
increasing = false; | |
currentLength = 2; // Reset current length for new subarray | |
} else { | |
currentLength++; | |
} | |
} else { | |
// Reset when the elements are equal | |
increasing = null; | |
currentLength = 1; | |
} | |
maxLength = Math.max(maxLength, currentLength); | |
} | |
return maxLength; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment