본문 바로가기
TIL

220518

by 김비누! 2022. 5. 18.

💻백준 2559: 수열

백준 2559

길이 N인 정수 수열에서 연속된 K개의 합 중 가장 큰 값을 구하는 문제이다.


위와 같이 슬라이딩 윈도우방식으로 currentSum을 구한다.

 

길이 N, 연속 범위 K, 정수 수열 순서로 입력이 주어진다.

초기 currentSum, max를 index 0 부터 index K-1의 합으로 정해
currentSum(이전에 구한 합)에서 현재 맨앞 인덱스(startIndex) 바로 전의 값을 빼고 startIndex +(k-1) 번째 배열 값을 더해
currentSum(현재 합)에 다시 넣는 방식으로 구현하였다.

    public static int initMax(int[] n, int K) {
        int result = 0;
        for(int i = 0; i < K; i++) {
            result += n[i];
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int K = sc.nextInt();

        int[] temperature = new int[N];
        for(int i = 0; i < temperature.length; i++) {
            temperature[i] = sc.nextInt();
        }

        int currentSum = initMax(temperature, K);/* index 0 ~ K-1 배열 합으로 초기화*/
        int max = currentSum;    /* 초기 max currentVal과 동일하게 설정 */
        /* 
         * 연속된 합의 처음 인덱스(startIndex) 1부터 시작 
         * 연속된 K개 합을 구해야 하므로 
         * startIndex 값의 범위 1 ~ temperature.length-K+1
         * */
        for(int startIndex = 1; startIndex < temperature.length-K+1; startIndex++) {
            currentSum = currentSum - temperature[startIndex-1] + temperature[startIndex+K-1];
            if(currentSum > max)
                max = currentSum;
        }
        System.out.println(max);
    }

🎯ETC

  • nbsp는 non-breaking space(줄바꿈없는 공백)의 약자

'TIL' 카테고리의 다른 글

220523  (0) 2022.05.23
220519  (0) 2022.05.19
220517  (0) 2022.05.17
220516  (0) 2022.05.16
220513: HTML document.write, JavaScript 배열 구조분해할당  (0) 2022.05.13

댓글