문제풀이/기타

[파이썬] [투포인터] 백준 20922 겹치는 건 싫어

승무_ 2023. 2. 24. 11:23

문제

https://www.acmicpc.net/problem/20922

 

20922번: 겹치는 건 싫어

홍대병에 걸린 도현이는 겹치는 것을 매우 싫어한다. 특히 수열에서 같은 원소가 여러 개 들어 있는 수열을 싫어한다. 도현이를 위해 같은 원소가 $K$개 이하로 들어 있는 최장 연속 부분 수열

www.acmicpc.net

코드

import sys
input=sys.stdin.readline

n,k=map(int, input().split())
array=list(map(int, input().split()))

left,right=0,0
count=[0]*(max(array)+1)
result=0

while right<n:
    if count[array[right]]<k:
        count[array[right]] += 1
        right+=1
    else:
        count[array[left]] -= 1
        left+=1
    result=max(result,right-left)

print(result)

시간 복잡도 

길이가 N인 수열을 순회하므로 O(N)