Skip to content

Latest commit

 

History

History
84 lines (58 loc) · 3.25 KB

File metadata and controls

84 lines (58 loc) · 3.25 KB

You are given an array of integers nums. Return the length of the longest subarray of nums which is either strictly increasing or strictly decreasing.

 

Example 1:

Input: nums = [1,4,3,3,2]

Output: 2

Explanation:

The strictly increasing subarrays of nums are [1], [2], [3], [3], [4], and [1,4].

The strictly decreasing subarrays of nums are [1], [2], [3], [3], [4], [3,2], and [4,3].

Hence, we return 2.

Example 2:

Input: nums = [3,3,3,3]

Output: 1

Explanation:

The strictly increasing subarrays of nums are [3], [3], [3], and [3].

The strictly decreasing subarrays of nums are [3], [3], [3], and [3].

Hence, we return 1.

Example 3:

Input: nums = [3,2,1]

Output: 3

Explanation:

The strictly increasing subarrays of nums are [3], [2], and [1].

The strictly decreasing subarrays of nums are [3], [2], [1], [3,2], [2,1], and [3,2,1].

Hence, we return 3.

 

Constraints:

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

Solution 1.

// OJ: https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int longestMonotonicSubarray(vector<int>& A) {
        auto find = [&](int sign) {
            int ans = 0, N = A.size();
            for (int i = 0; i < N; ++i) {
                int start = i;
                while (i + 1 < N && (A[i + 1] > A[i] ? 1 : (A[i + 1] < A[i] ? -1 : 0)) == sign) ++i;
                ans = max(ans, i - start + 1);
            }
            return ans;
        };
        return max(find(1), find(-1));
    }
};