래원

[LeetCode] 3105. Longest Strictly Increasing or Strictly Decreasing Subarray (Python) 본문

알고리즘/LeetCode

[LeetCode] 3105. Longest Strictly Increasing or Strictly Decreasing Subarray (Python)

Laewon Jeong 2025. 2. 3. 12:40

 

 

난이도: Easy

문제 설명


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.

 

제한 사항


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

 

✏️ Solution(솔루션)


class Solution:
    def longestMonotonicSubarray(self, nums: List[int]) -> int:
        answer = 1
        n = len(nums)
        is_len, ds_len = 1, 1

        for i in range(n-1):
            if nums[i] < nums[i+1]:
                is_len += 1
                ds_len = 1
            elif nums[i] > nums[i+1]:
                ds_len += 1
                is_len = 1
            else:
                is_len = 1
                ds_len = 1
            
            answer = max(answer, is_len, ds_len)

        return answer

 

nums의 현재 요소와 다음 요소를 비교하여 다음 요소가 더 크다고 한다면 strictly increasing subarray를 만족하기에 is_len을 +1 해주고 ds_len을 1로 설정했다.

 

반대로 현재 요소와 다음 요소를 비교하여 다음 요소가 더 작다고 한다면 strictly decreasing subarray를 만족하기에 ds_len을 +1 해주고 is_len을 1로 설정했다.

 

현재 요소와 다음 요소가 같다고 한다면 어느것도 만족하지 않기에 is_len, ds_len 모두 1로 설정해주었다.

 

현재 요소의 비교가 끝났다면 max함수를 통해 answer를 업데이트 했다.

 

모든 요소의 비교가 끝나면 answer를 return하고 정답을 맞출 수 있었다.


문제: 3105. Longest Strictly Increasing or Strictly Decreasing Subarray

 

깃허브: github

 

algorithmPractice/LeetCode/3372-longest-strictly-increasing-or-strictly-decreasing-subarray at main · laewonJeong/algorithmPrac

하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.

github.com