물음표 살인마의 개발블로그

알고리즘 문제/백준

The Pleasant Walk #19829

BEstyle 2023. 1. 11. 06:37

문제

There are n houses along the road where Anya lives, each one is painted in one of k possible colors.

Anya likes walking along this road, but she doesn't like when two adjacent houses at the road have the same color. She wants to select a long segment of the road such that no two adjacent houses have the same color.

Help Anya find the longest segment with this property.

입력

The first line contains two integers n and k --- the number of houses and the number of colors (1≤n≤100000, 1≤k≤100000).

The next line contains n integers a1,a2,…,an --- the colors of the houses along the road (1≤ai≤k).

출력

Output a single integer --- the maximum number of houses on the road segment having no two adjacent houses of the same color.

예제 입력 1 복사

8 3
1 2 3 3 2 1 2 2

예제 출력 1 복사

4

힌트

In the example, the longest segment without neighboring houses of the same color is from the house 4 to the house 7. The colors of the houses are [3,2,1,2] and its length is 4 houses.

알고리즘 분류


# https://www.acmicpc.net/problem/19829

'''
1. 아이디어 :
    1) 두 포인터로, lp=0, rp=0로 지정한 후, rp와 rp+1이 같다면, rp-lp+1로 max를 갱신해주고, rp+1에 lp와 rp를 둔다.
2. 시간복잡도 :
    1) O(n)
3. 자료구조 :
    1) 배열
'''

import sys

input = sys.stdin.readline
n, k = map(int, input().split())
nums = list(map(int, input().split()))
if n==1:
    print(1)
    exit()
lp, rp = 0, 0
cmax = 1
while True:
    if nums[rp]==nums[rp+1]:
        cmax = max(cmax, rp-lp+1)
        rp+=1
        lp=rp
    else:
        rp+=1
    if rp==len(nums)-1:
        cmax = max(cmax, rp-lp+1)
        break
print(cmax)

'알고리즘 문제 > 백준' 카테고리의 다른 글

소가 길을 건너간 이유 5 #14465  (0) 2023.01.12
문자열 교환 #1522  (0) 2023.01.11
코스튬 파티 #6159  (0) 2023.01.11
에디터 #1406  (0) 2023.01.11
쇠막대기 #10799  (0) 2023.01.11