[백준/C++] 2495 - 연속구간

orangesnail·2025년 7월 18일

백준

목록 보기
114/169

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


구현하기

오랜만에 코드를 짜니 모든걸 까먹었다...

처음 짠 엉망 코드는 아래와 같다

#include <iostream>
using namespace std;

int main() {
    for (int j = 0; j < 3; j++) {
        string num;
        cin >> num;

        int max_count = 0, current_count = 0;

        for (int i = 1; i < num.length(); i++) {
            if (num[i] == num[i - 1]) current_count++;
            else {
                max_count = current_count;
                current_count = 1;
            }
        }
        max_count = current_count;

        cout << max_count << endl;
    }
    return 0;
}

여기서의 문제점
1. current_count는 초기값이 0이 아니라 1이 되어야 한다. 문자가 하나일 때부터 세는 거니까!
2. max_count를 업데이트 해줄 때는 덮어쓰는게 아니라, 현재의 max_count와 current_count 중에서 더 큰 것을 새로운 max_count으로 선정해야 한다. 😞

수정된 전체 코드

#include <iostream>
using namespace std;

int main() {
    for (int j = 0; j < 3; j++) {
        string num;
        cin >> num;

        int max_count = 0, current_count = 1;

        for (int i = 1; i < num.length(); i++) {
            if (num[i] == num[i - 1]) current_count++;
            else {
                max_count = max(max_count, current_count);
                current_count = 1;
            }
        }
        max_count = max(max_count, current_count);

        cout << max_count << endl;
    }
    return 0;
}

이번 문제는 c++ 감 되찾는 용으로....

profile
초보입니다. 피드백 환영합니다 😗

0개의 댓글