알고리즘

백준 21921번 블로그 (JAVA)

박카스마시며코딩 2022. 8. 12. 10:09

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

 

21921번: 블로그

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

www.acmicpc.net

 

저는 슬라이딩 윈도우를 통해 문제를 해결하였습니다.

슬라이딩 윈도우를 통해 x의 간격의 각각 합을 구하고 각각의 합을 비교해 이때 최대를 구하고 개수를 구하였습니다.

 

package BOJ.twopoint;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_21921 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(st.nextToken());
        int m = stoi.apply(st.nextToken());
        st = new StringTokenizer(br.readLine());
        int[] input = new int[n];
        for(int i = 0 ; i < n ; i++){
            input[i] = stoi.apply(st.nextToken());
        }
        cal(input,n,m);
    }
    private static final String NOT_FOUND = "SAD";
    private static void cal(int[] input, int n, int m) {
        int cnt = 0;
        int max = 0;
        int sum = 0;
        for(int i = 0 ; i < n ; i++){
            sum += input[i];
            if(i >= m){
                sum -= input[i-m];
            }
            if(i >= m-1){
                if(max < sum){
                    max = sum;
                    cnt = 0;
                }
                if(max == sum){
                    cnt++;
                }
            }

        }
        if(max == 0){
            System.out.println(NOT_FOUND);
            return;
        }
        System.out.println(max);
        System.out.println(cnt);
    }
}