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)
참고:
728x90
'코딩 테스트' 카테고리의 다른 글
[LeetCode] 1726. Tuple with Same Product (Python) (0) | 2025.02.07 |
---|---|
[LeetCode] 1800. Maximum Ascending Subarray Sum (Python) (0) | 2025.02.04 |
[LeetCode] 1752. Check if Array Is Sorted and Rotated (Python) (0) | 2025.02.02 |
[LeetCode] 637. Average of Levels in Binary Tree (Python) (0) | 2025.02.01 |
[LeetCode] 3151. Special array 1 (Python) (0) | 2025.02.01 |
댓글