๊ธฐ๋ก๋ฐฉ

BOJ_2559 : ์ˆ˜์—ด ๋ณธ๋ฌธ

CodingTest/Java

BOJ_2559 : ์ˆ˜์—ด

Soom_1n 2023. 1. 12. 09:18

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

2559๋ฒˆ: ์ˆ˜์—ด

์ฒซ์งธ ์ค„์—๋Š” ๋‘ ๊ฐœ์˜ ์ •์ˆ˜ N๊ณผ K๊ฐ€ ํ•œ ๊ฐœ์˜ ๊ณต๋ฐฑ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ˆœ์„œ๋Œ€๋กœ ์ฃผ์–ด์ง„๋‹ค. ์ฒซ ๋ฒˆ์งธ ์ •์ˆ˜ N์€ ์˜จ๋„๋ฅผ ์ธก์ •ํ•œ ์ „์ฒด ๋‚ ์งœ์˜ ์ˆ˜์ด๋‹ค. N์€ 2 ์ด์ƒ 100,000 ์ดํ•˜์ด๋‹ค. ๋‘ ๋ฒˆ์งธ ์ •์ˆ˜ K๋Š” ํ•ฉ์„ ๊ตฌํ•˜๊ธฐ

www.acmicpc.net



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • n๊ฐœ์˜ ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆ˜์—ด์—์„œ ์—ฐ์†๋œ k๊ฐœ๋ฅผ ๊ณจ๋ž์„ ๋•Œ ๊ทธ ํ•ฉ์˜ ์ตœ๋Œ€๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.
  • ์ „ํ˜•์ ์ธ ๋‘ ํฌ์ธํ„ฐ, ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ ๋ฌธ์ œ์ด๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
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 k = Integer.parseInt(st.nextToken());
        int[] arr = new int[n];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        int lp = 0, rp = k-1;
        int sum = 0;
        for (int i = lp; i <= rp; i++) {
            sum += arr[i];
        }

        int answer = sum;
        for (int i = 0; i < n-k; i++) {
            sum -= arr[lp++];
            sum += arr[++rp];
            if (sum > answer)
                answer = sum;
        }
        System.out.println(answer);
    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • k๋งŒํผ ์ฐจ์ด๋‚˜๋Š” ๋‘ ํฌ์ธํ„ฐ lp์™€ rp๋กœ ํ•ฉ์„ ๊ณ„์‚ฐํ•œ๋‹ค.
    • lp์™€ rp๋ฅผ 1์”ฉ ์ฆ๊ฐ€ํ•ด๊ฐ€๋ฉฐ, arr[lp] ๊ฐ’์€ ํ•ฉ์—์„œ ๋นผ์ฃผ๊ณ  arr[rp] ๊ฐ’์€ ๋”ํ•ด์ค€๋‹ค.
  • ํ•ฉ์˜ ์ตœ๋Œ€๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋Š” ์˜ค๋žœ๋งŒ์— ํ’€์–ด๋ณด๋Š”๋ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์•Œ๊ณ ์žˆ์œผ๋‹ˆ ๊ฐ„๋‹จํ–ˆ๋‹ค.
  • ๋งˆ์ง€๋ง‰ for๋ฌธ์—์„œ i๊ฐ’์„ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์•ผํ•˜๋Š”๋ฐ 1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ 1ํšŒ ํ‹€๋ ธ๋‹ค.

728x90