[백준/2559] 수열 - JAVA

이지환·2023년 12월 19일

알고리즘(백준) 💻

목록 보기
9/80
post-thumbnail

📌 문제

알고리즘 분류 : 투포인터, 누적합
난이도 : 실버3
출처 : 백준 - 수열

🦧 문제 풀이 접근

배열에 0부터 현재 index까지의 값을 누적해서 대입한다.
배열에 맨 앞부터 M번째 칸까지의 합을 구한 후 한칸씩 뒤로가면서 최대값을 찾는다.

💻 code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());
        int[] arr = new int[N+2];
        int max = Integer.MIN_VALUE;
        st = new StringTokenizer(br.readLine()," ");
        arr[0]=0;
        for(int i=1;i<=N;i++) {
            arr[i] = arr[i-1]+Integer.parseInt(st.nextToken());
        }
        for(int i=1;i<=N-M+1;i++) {
            if(max<arr[i+M-1]-arr[i-1])
                max=arr[i+M-1]-arr[i-1];
        }
        System.out.println(max);
    }
}

🥇 결과

🎓 느낀점

투포인터, 누적합 기초 문제다. 반복문을 중첩해서 코드를 작성하면 시간초과가 발생할 수 있다.

profile
takeitEasy

0개의 댓글