3105. Longest Strictly Increasing or Strictly Decreasing Subarray

LeetCode 力扣

1. Description

Given an integer array nums, return the maximum length of a contiguous subarray whose values strictly increase or strictly decrease.

2. Example

Example 1

Input: nums = [1,4,3,3,2]
Output: 2
Explanation: [1,4] strictly increases, while [4,3] and [3,2] strictly decrease. Each has length 2.

Example 2

Input: nums = [3,3,3,3]
Output: 1
Explanation: Equal adjacent values cannot belong to a strictly increasing or strictly decreasing subarray, so only single-element subarrays qualify.

Example 3

Input: nums = [3,2,1]
Output: 3
Explanation: The entire array strictly decreases.

3. Constraints

  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= 50

4. Solutions

greedy

n = nums.size()
Time complexity: O(n)
Space complexity: O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    int longestMonotonicSubarray(const vector<int> &nums) {
        const int n = nums.size();

        int max_length = 1;
        int max_increase = 1, max_decrease = 1;
        for (int i = 1; i < n; ++i) {
            if (nums[i] > nums[i - 1]) {
                ++max_increase;
                max_decrease = 1;
                max_length = max(max_length, max_increase);
            } else if (nums[i] < nums[i - 1]) {
                ++max_decrease;
                max_increase = 1;
                max_length = max(max_length, max_decrease);
            } else {
                max_increase = max_decrease = 1;
            }
        }

        return max_length;
    }
};
comments powered by Disqus