1. 문제 설명
https://www.acmicpc.net/problem/2491
2491번: 수열
0에서부터 9까지의 숫자로 이루어진 N개의 숫자가 나열된 수열이 있다. 그 수열 안에서 연속해서 커지거나(같은 것 포함), 혹은 연속해서 작아지는(같은 것 포함) 수열 중 가장 길이가 긴 것을 찾
www.acmicpc.net
2. 아이디어
쉽고 간단하고 재밌는 문제.
수열을 훑으면서 오름차순과 내림차순인 경우를 동시에 판단하면 된다.
오름차순이면 decending을 초기화하고, 내림차순이면 ascending을 초기화한다.
만약 값이 같다면 ascending과 decending 모두 1씩 증가시키면서 max값을 갱신하다가
마지막에 더 큰 값을 출력하면 끝난다.
3. 코드
def read_sequence(sequence, n, max_a, max_d):
ascending, decending = 0, 0
for idx in range(n):
if sequence[idx - 1] < sequence[idx]:
ascending += 1
max_d = max(max_d, decending)
decending = 1
elif sequence[idx - 1] > sequence[idx]:
decending += 1
max_a = max(max_a, ascending)
ascending = 1
else:
ascending += 1
decending += 1
max_a = max(max_a, ascending)
max_d = max(max_d, decending)
return max_a, max_d
def solution():
n = int(input())
sequence = list(map(int, input().split()))
max_a, max_d = 1, 1
if n == 1:
print(1)
return
max_a, max_d = read_sequence(sequence, n, max_a, max_d)
print(max(max_a, max_d))
solution()