Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 아파치 카프카
- BFS
- 프로그래머스
- 우선순위큐
- leetcode
- DP
- heapq
- 파이썬
- Apache Hadoop
- 문자열
- docker
- 아파치 하둡
- String
- 아파치 스파크
- 티스토리챌린지
- 분산
- apache kafka
- 이진탐색
- programmers
- 분산처리
- 그래프
- 카프카
- 하둡
- Python
- 코딩테스트
- Apache Spark
- 오블완
- 알고리즘
- 도커
- 리트코드
Archives
- Today
- Total
래원
[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 ofnums
are[1]
,[2]
,[3]
,[3]
,[4]
, and[1,4]
.
The strictly decreasing subarrays ofnums
are[1]
,[2]
,[3]
,[3]
,[4]
,[3,2]
, and[4,3]
.
Hence, we return2
.
Example 2:
Input: nums = [3,3,3,3]
Output: 1
Explanation:
The strictly increasing subarrays ofnums
are[3]
,[3]
,[3]
, and[3]
.
The strictly decreasing subarrays ofnums
are[3]
,[3]
,[3]
, and[3]
.
Hence, we return1
.
Example 3:
Input: nums = [3,2,1]
Output: 3
Explanation:
The strictly increasing subarrays ofnums
are[3]
,[2]
, and[1]
.
The strictly decreasing subarrays ofnums
are[3]
,[2]
,[1]
,[3,2]
,[2,1]
, and[3,2,1]
.
Hence, we return3
.
제한 사항
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
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 1752. Check if Array Is Sorted and Rotated (Python) (0) | 2025.02.02 |
---|---|
[LeetCode] 3151. Special Array I (Python) (0) | 2025.02.01 |
[LeetCode] 827. Making A Large Island (Python) (0) | 2025.01.31 |
[LeetCode] 785. Is Graph Bipartite? (Python) (0) | 2025.01.30 |
[LeetCode] 2658. Maximum Number of Fish in a Grid (Python) (0) | 2025.01.28 |