백준

백준 20922 겹치는 건 싫어 c++

2024. 4. 7. 21:15

 

 

 

처음 작성한 코드는 다음과 같다.

하지만 틀렸다는 결과가 나왔다.

#include <iostream>
using namespace std;

int main(){
    int n,k;
    cin >> n >> k;
    
    int arr[n];
    for(int i=0; i<n; i++)
        cin >> arr[i];
    
    int length = 1;
    int same = 1;
    int max_length = 1; //arr[0]를 고려해준 것임
    
    for(int i=1; i<n; i++){
        length++;
        if(arr[i-1] == arr[i]){
            same++;
            if(same == k){
                if(max_length < length)
                    max_length = length;
                same = 1;
                length = 1;
            }
        }
        else{ //arr[i-1] != arr[i]
           if(same == k){
                if(max_length < length)
                    max_length = length;
                same = 1;
                length = 1;
            } 
        }
    }
    
    cout << max_length;
    
    return 0;
}

 

 

 

다시 작성해서 해결했다.

가장 긴 경우 수열 시작 인덱스 "start" 변수를 사용해 수열의 길이를 계산하도록 한다.

count배열을 사용해 숫자가 나올 때 마다 해당 인덱스를 ++해서 해당 숫자가 나타난 개수를 센다.

 

 

 

 

 

'백준' 카테고리의 다른 글

백준 15059 Hard choice c++  (0) 2024.04.09
백준 16967 배열 복원하기 c++  (0) 2024.04.08
백준 8979 올림픽 c++  (0) 2024.04.06
백준 2075 N번째 큰 수 c++  (0) 2024.04.05
백준 19637 IF문 좀 대신 써줘 c++  (0) 2024.04.05