새소식

Algorithm/BOJ

(JAVA) [BOJ]백준 21921번, 블로그

  • -
728x90

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

 

21921번: 블로그

첫째 줄에 $X$일 동안 가장 많이 들어온 방문자 수를 출력한다. 만약 최대 방문자 수가 0명이라면 SAD를 출력한다. 만약 최대 방문자 수가 0명이 아닌 경우 둘째 줄에 기간이 몇 개 있는지 출력한다

www.acmicpc.net

21921, 블로그

[ 난이도 : 실버 3 ]

이번 문제는 투포인터 생각났지만 단순 반복문으로 풀이했다.

 

Process

input

: 방문자 수 N 과 연속으로 확인 할 일수인 M 을 입력받고 배열을 생성해준다.

static int N, M;
static int[] arr;

static void input() 
{
    N = scan.nextInt(); M = scan.nextInt();
    arr = new int[N];
    for(int i=0; i<N; i++) arr[i] = scan.nextInt();
}

 

구현

: 연속으로 방문한 방문자 수를 입력할 ArrayList 를 선언해준다.

처음 연속 방문자 수를 체크하고 score에 넣어주고 max 값으로 선언해준다.

int value = 0;

for(int i=0;i<M; i++) value += arr[i];
score.add(value);
int max = value;

 

처음 방문자 수를 계산했으니 다음 로직을 생각해보자.

이제부터는 매번 계산을 할 필요없이 맨 앞에 값을 빼주고 그 다음 수를 추가해주면 된다.

다시 계산한 값을 score 에 넣어주고 max 값을 갱신해주면 된다.

for(int i=1; i<=N-M; i++) // 3
{
    value -= arr[i-1];
    value += arr[i+M-1];

    score.add(value);

    if(max < value) max = value;
}

 

 

그 후에 score를 순회하며 최대값과 같은 경우를 찾아 cnt 를 계산해주고 출력해주면 끝이다.

int cnt = 0;
for(int i=0; i<score.size(); i++)
{
    if(score.get(i) == max) cnt++;
}
if(max == 0)
    System.out.println("SAD");
else
    System.out.println(max+"\n"+cnt);

 

전체 코드

: 크게 어려울게 없는 구현문제였다.

static int N, M;
static int[] arr;

static void input() 
{
    N = scan.nextInt(); M = scan.nextInt();
    arr = new int[N];
    for(int i=0; i<N; i++) arr[i] = scan.nextInt();
}

static void pro() 
{   
    ArrayList<Integer> score = new ArrayList<>();

    int value = 0;

    for(int i=0;i<M; i++) value += arr[i];
    score.add(value);
    int max = value;

    for(int i=1; i<=N-M; i++)
    {
        value -= arr[i-1];
        value += arr[i+M-1];

        score.add(value);

        if(max < value) max = value;
    }

    int cnt = 0;
    for(int i=0; i<score.size(); i++)
    {
        if(score.get(i) == max) cnt++;
    }
    if(max == 0)
        System.out.println("SAD");
    else
        System.out.println(max+"\n"+cnt);
}

public static void main(String[] args) 
{
    input();
    pro();	
}

 

728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.