Understand Maximum length of Strictly Increasing or Strictly Decreasing Subarray Problem

Problem: Maximum length of Strictly Increasing or Strictly Decreasing Subarray

Problem Statement

You are given an array of integers nums. Your task is to find the length of the longest strictly increasing or strictly decreasing contiguous subarray.

Constraints

  • A subarray is a contiguous part of the array.
  • A strictly increasing subarray means each element is greater than the previous one.
  • A strictly decreasing subarray means each element is smaller than the previous one.
  • The array may contain duplicate values, which break the strict order.

Example 1

Input:

nums = [2, 5, 7, 6, 4]

Output:

3

Explanation:

  • Strictly increasing subarrays: [2], [5], [7], [6], [4], [2,5], [5,7], [2,5,7]
  • Strictly decreasing subarrays: [2], [5], [7], [6], [4], [7,6], [6,4], [7,6,4]
  • Longest valid subarray: [7,6,4] (length = 3)

Example 2

Input:

nums = [8, 8, 8, 8]

Output:

1

Explanation:

  • No valid increasing or decreasing sequence of length > 1.
  • The longest valid subarray is just any single element (length = 1).

Example 3

Input:

nums = [9, 7, 5, 3, 1]

Output:

5

Explanation:

  • Strictly decreasing subarrays: [9], [7], [5], [3], [1], [9,7], [7,5], [5,3], [3,1], [9,7,5], [7,5,3], [5,3,1], [9,7,5,3], [7,5,3,1], [9,7,5,3,1]
  • Longest valid subarray: [9,7,5,3,1] (length = 5)

Additional Test Cases

Test Case 4

Input:
nums = [12, 14, 16, 13, 11, 9]
Output:
4
Explanation:
  • Strictly increasing subarrays: [12], [14], [16], [13], [11], [9], [12,14], [14,16], [12,14,16]
  • Strictly decreasing subarrays: [12], [14], [16], [13], [11], [9], [16,13], [13,11], [11,9], [16,13,11], [13,11,9], [16,13,11,9]
  • Longest valid subarray: [16,13,11,9] (length = 4)

Test Case 5

Input:
nums = [1, 3, 5, 7, 9]
Output:
5
Explanation:
  • Strictly increasing subarrays: [1], [3], [5], [7], [9], [1,3], [3,5], [5,7], [7,9], [1,3,5], [3,5,7], [5,7,9], [1,3,5,7], [3,5,7,9], [1,3,5,7,9]
  • No decreasing subarrays exist.
  • Longest valid subarray: [1,3,5,7,9] (length = 5)
Category:
  • Leetcode Problem of the Day
Programming Language:
  • Java
Reference Link:

https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray/description/?envType=daily-question&envId=2025-02-03

Java
Output:

Loading component...

Loading component...