본문 바로가기
코딩 테스트

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

by zoodi 2025. 2. 3.
728x90

Problem

 

Solution

sliding window

for문으로 하나씩 값을 비교해가면서 decrease, increase 하는 sub array의 최대 길이값을 계산하는 문제.

이때 strictly inc/dec 라서 동일한 숫자가 나오면 안된다.

 

for문 하나로 해결하는게 관건!

 

처음에 아래 다른사람 코드처럼 increasing, decreasing 하는 로직으로 나누어서 푸려고했는데 간과한 점이 있었다.

  • for문을 돌때 0번째가 아닌 1번 인덱스부터 앞 값과 비교할 것
  • 만약 increasing check 의 경우 nums[i] > num[i-1] 가 아니면 tmp_count =1 로 리셋할 것
class Solution:
    def longestMonotonicSubarray(self, nums: List[int]) -> int:
        temp_count = 1
        n = len(nums)
        max_v = 1
        for i in range (1, n):
            if nums[i] > nums[i-1]:
                temp_count += 1
                max_v = max(temp_count, max_v)
            else:
                temp_count = 1
        temp_count = 1
        for i in range (1,n):
            if nums[i] < nums[i-1]:
                temp_count += 1                
                max_v = max(temp_count, max_v)
            else:
                temp_count = 1
        return max_v

 

 

Code

class Solution:
    def longestMonotonicSubarray(self, nums: List[int]) -> int:
        answer = 1
        inc = 1
        dec = 1

        for i in range(1, len(nums)):
            #strictly increasing
            if nums[i] > nums[i-1]:
                inc += 1
                dec = 1 #reset decreasing
            #strictly decreasing
            elif nums[i] < nums[i-1]:
                inc = 1 #reset increasing
                dec += 1
            #equal num
            else:
                inc = dec = 1
            answer = max(max(inc, dec), answer)
        return answer

 

Complexity

Time Complexity

O(N)

 

Space Complexity

사용한 변수 answer, inc, dec => O(1)


참고:

https://medium.com/@cyberseize/leetcode-3105-longest-strictly-increasing-or-strictly-decreasing-subarray-b55af76d34c0

728x90

댓글