3105. Longest Strictly Increasing or Strictly Decreasing Subarray
/**
* Problem: LeetCode 3105 - Longest Strictly Increasing or Strictly Decreasing Subarray
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int longestMonotonicSubarray(int[] nums) {
int inc = 1, dec = 1, ans = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
inc++;
dec = 1;
} else if (nums[i] < nums[i - 1]) {
dec++;
inc = 1;
} else {
inc = 1;
dec = 1;
}
ans = Math.max(ans, Math.max(inc, dec));
}
return ans;
}
}
"""
Problem: LeetCode 3105 - Longest Strictly Increasing or Strictly Decreasing Subarray
Difficulty: Easy
Language: Python 3
Author: CodeByTushu
"""
from typing import List
class Solution:
def longestMonotonicSubarray(self, nums: List[int]) -> int:
inc = 1
dec = 1
ans = 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 = 1
dec = 1
ans = max(ans, inc, dec)
return ans
/**
* Problem: LeetCode 3105 - Longest Strictly Increasing or Strictly Decreasing Subarray
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
class Solution {
public:
int longestMonotonicSubarray(std::vector<int>& nums) {
int inc = 1, dec = 1, ans = 1;
for (int i = 1; i < static_cast<int>(nums.size()); ++i) {
if (nums[i] > nums[i - 1]) {
++inc;
dec = 1;
} else if (nums[i] < nums[i - 1]) {
++dec;
inc = 1;
} else {
inc = 1;
dec = 1;
}
ans = std::max({ans, inc, dec});
}
return ans;
}
};
/**
* Problem: LeetCode 3105 - Longest Strictly Increasing or Strictly Decreasing Subarray
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number[]} nums
* @return {number}
*/
var longestMonotonicSubarray = function(nums) {
let inc = 1, dec = 1, ans = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
inc++;
dec = 1;
} else if (nums[i] < nums[i - 1]) {
dec++;
inc = 1;
} else {
inc = 1;
dec = 1;
}
ans = Math.max(ans, inc, dec);
}
return ans;
};