LeetCode 3105: Longest Strictly Increasing or Strictly Decreasing Subarray Solution
Master LeetCode problem 3105 (Longest Strictly Increasing or Strictly Decreasing Subarray), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3105. Longest Strictly Increasing or Strictly Decreasing Subarray
Problem Explanation
Explanation
To solve this problem, we can iterate through the array and keep track of the current increasing or decreasing sequence length. We maintain two variables inc and dec to represent the lengths of the current increasing and decreasing sequences respectively. When the current element is greater than the previous element, we increment inc and reset dec to 1. Similarly, when the current element is less than the previous element, we increment dec and reset inc to 1. We update the maximum length of the increasing or decreasing sequence found so far and return it as the result.
- Time complexity: O(n) where n is the number of elements in the input array.
- Space complexity: O(1)
Solution Code
class Solution {
public int longestSubarray(int[] nums) {
if (nums.length == 1) {
return 1;
}
int inc = 1, dec = 1;
int maxLen = 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;
}
maxLen = Math.max(maxLen, Math.max(inc, dec));
}
return maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3105 (Longest Strictly Increasing or Strictly Decreasing Subarray)?
This page provides optimized solutions for LeetCode problem 3105 (Longest Strictly Increasing or Strictly Decreasing Subarray) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3105 (Longest Strictly Increasing or Strictly Decreasing Subarray)?
The time complexity for LeetCode 3105 (Longest Strictly Increasing or Strictly Decreasing Subarray) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3105 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3105 in Java, C++, or Python.