3105. Longest Strictly Increasing or Strictly Decreasing Subarray #1265
-
Topics: You are given an array of integers nums. Return the length of the longest subarray1 of nums which is either strictly increasing2 or strictly decreasing3. Example 1:
Example 2:
Example 3:
Constraints:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the length of the longest subarray that is either strictly increasing or strictly decreasing. Here's a step-by-step approach to achieve this:
Let's implement this solution in PHP: 3105. Longest Strictly Increasing or Strictly Decreasing Subarray <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function longestMonotonicSubarray($nums) {
$n = count($nums);
if ($n == 0) return 0;
$maxLen = 1;
$incLen = 1;
$decLen = 1;
for ($i = 1; $i < $n; $i++) {
if ($nums[$i] > $nums[$i - 1]) {
$incLen++;
$decLen = 1;
} elseif ($nums[$i] < $nums[$i - 1]) {
$decLen++;
$incLen = 1;
} else {
$incLen = 1;
$decLen = 1;
}
if ($incLen > $maxLen) {
$maxLen = $incLen;
}
if ($decLen > $maxLen) {
$maxLen = $decLen;
}
}
return $maxLen;
}
// Example usage:
$nums1 = [1, 4, 3, 3, 2];
echo longestMonotonicSubarray($nums1); // Output: 2
$nums2 = [3, 3, 3, 3];
echo longestMonotonicSubarray($nums2); // Output: 1
$nums3 = [3, 2, 1];
echo longestMonotonicSubarray($nums3); // Output: 3
?> Explanation:
This approach ensures that we efficiently find the longest subarray that is either strictly increasing or strictly decreasing in linear time complexity, O(n), where n is the length of the array. |
Beta Was this translation helpful? Give feedback.
We need to find the length of the longest subarray that is either strictly increasing or strictly decreasing. Here's a step-by-step approach to achieve this:
Initialize Variables: We'll need variables to keep track of the lengths of the current increasing and decreasing subarrays, as well as the maximum length found so far.
Iterate Through the Array: We'll loop through the array and compare each element with the previous one to determine if the current subarray is increasing, decreasing, or neither.
Update Lengths: Depending on the comparison, we'll update the lengths of the current increasing or decreasing subarrays.
Update Maximum Length: After each comparison, we'll update the …