Leetcode 3105. Longest Strictly Increasing or Strictly Decreasing Subarray
You are given an integer array nums
. A subarray of a given array is called strictly increasing if all the elements of this subarray are in increasing order, and strictly decreasing if all the elements of this subarray are in decreasing order. Return the length of the longest subarray that is either strictly increasing or strictly decreasing.
10^5
elements.inc
and dec
, to keep track of the current length of strictly increasing and strictly decreasing subarrays.max_length
, inc
, and dec
to store the maximum required length and current lengths of subarrays.inc
and reset dec
if a strictly increasing sequence is found.dec
and reset inc
if a strictly decreasing sequence is found.max_length
with the maximum value of inc
or dec
.max_length
.Here’s how you might implement this algorithm in C++:
#include <vector>
#include <algorithm>
int longest_strictly_inc_or_dec_subarray(const std::vector<int>& nums) {
int inc = 1, dec = 1, max_length = 1;
// Edge case for empty array
if (nums.empty()) {
return 0;
}
for (size_t i = 1; i < nums.size(); ++i) {
if (nums[i] > nums[i - 1]) {
inc = dec + 1;
dec = 1;
} else if (nums[i] < nums[i - 1]) {
dec = inc + 1;
inc = 1;
} else {
inc = dec = 1;
}
max_length = std::max(max_length, std::max(inc, dec));
}
return max_length;
}
The time complexity of this approach is O(n) where n
is the length of the input array nums
. This is because we are traversing the array exactly once.
The space complexity is O(1) as only a constant amount of extra space is used, regardless of the input array size.
This ensures the solution is efficient and can handle large input sizes within typical constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?