Strictly Increasing & Strictly Decreasing Subarray
"Strictly Increasing" 과 "Strictly Decreasing"은 다음을 뜻한다.
인접한 행렬이 점점 숫자가 커지면 Strictly Increasing
인접한 행렬이 점점 숫자가 작아지면 Strictly Decresing
두 경우 모두 원소가 한 개인 경우를 모두 포함한다.
중복된 값은 별개의 것으로 친다.
예를 들어 배열이 [1,4,3,3,2]일 경우
- Strictly Increasing: [1], [4], [3], [3], [2], [1, 4]
- Strictly Decreasing: [1], [4], [3], [3], [2], [4, 3], [3, 2]
예를 들어 배열이 [3,2,1]일 경우
- Strictly Increasing: [3], [2], [1]
- Strictly Decreasing: [3], [2], [1], [3, 2], [2, 1], [3, 2, 1]
같은 숫자가 연속해서 오거나, 인접한 배열 원소가 Increasing 하거나 Decreasing 하는 규칙을 위배할 경우 포함되지 않는다.
Problem
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.
nums라는 정수 배열이 주어졌을 때, Strictly Increasing하거나 Decreasing하는 Subarray중 가장 긴 것의 길이를 반환하는 문제이다.
예를 들어 [1,4,3,3,2] 일 경우 가장 긴 Subarray는 [4, 3], [3, 2]로 2를 반환한다.
예를 들어 [3,2,1] 일 경우 가장 긴 Subarray는 [3,2,1]로 3을 반환한다.
class Solution(object):
def longestMonotonicSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_len = inc_len = dec_len = 1
for i in range(len(nums)-1):
inc_len = inc_len + 1 if nums[i] < nums[i+1] else 1
dec_len = dec_len + 1 if nums[i] > nums[i+1] else 1
max_len = max(max_len, inc_len, dec_len)
return max_len
inc_len은 Strictly Increasing Subarray의 길이를 나타내고, dec_len은 Strictly Decreasing Subarray의 길이를 나타낸다.
for 루프를 돌며 전체 인접한 배열 쌍끼리의 크기를 비교하는데,
- 만약에 앞 수가 뒤 수보다 클 경우 Increasing Subarray의 집계는 끝나고 1부터 다시 시작해야 하고
- 만약에 앞 수가 뒤 수보다 작을 경우 Decreasing Subarray의 집계는 끝나고 1부터 다시 시작해야 한다.
동시에 각 Strict 조건을 만족하기도 하므로 Increasing 혹은 Decreasing Subarray의 개수는 늘어난다.
for 루프를 돌 때마다 가장 큰 값을 저장하여 다음 루프로 넘긴다.