01-25 03:45
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_26 ์ตœ๋Œ€ ๋งค์ถœ ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_26 ์ตœ๋Œ€ ๋งค์ถœ

miinsun 2022. 1. 4. 12:46

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

ํ˜„์ˆ˜์˜ ์•„๋น ๋Š” ์ œ๊ณผ์ ์„ ์šด์˜ํ•ฉ๋‹ˆ๋‹ค. ํ˜„์ˆ˜ ์•„๋น ๋Š” ํ˜„์ˆ˜์—๊ฒŒ N์ผ ๋™์•ˆ์˜ ๋งค์ถœ๊ธฐ๋ก์„ ์ฃผ๊ณ  ์—ฐ์†๋œ K์ผ ๋™์•ˆ์˜ ์ตœ๋Œ€ ๋งค์ถœ์•ก์ด ์–ผ๋งˆ์ธ์ง€ ๊ตฌํ•˜๋ผ๊ณ  ํ–ˆ์Šต๋‹ˆ๋‹ค.

๋งŒ์•ฝ N=10์ด๊ณ  10์ผ ๊ฐ„์˜ ๋งค์ถœ๊ธฐ๋ก์ด ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

์ด๋•Œ K=3์ด๋ฉด
12 15 11 20 25 10 20 19 13 15

์—ฐ์†๋œ 3์ผ๊ฐ„์˜ ์ตœ๋Œ€ ๋งค์ถœ์•ก์€ 11+20+25=56๋งŒ์›์ž…๋‹ˆ๋‹ค.
์—ฌ๋Ÿฌ๋ถ„์ด ํ˜„์ˆ˜๋ฅผ ๋„์™€์ฃผ์„ธ์š”.

 

 

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ์ค„์— N(5<=N<=100,000)๊ณผ K(2<=K<=N)๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

๋‘ ๋ฒˆ์งธ ์ค„์— N๊ฐœ์˜ ์ˆซ์ž์—ด์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ๊ฐ ์ˆซ์ž๋Š” 500์ดํ•˜์˜ ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜์ž…๋‹ˆ๋‹ค.

10 3
12 15 11 20 25 10 20 19 13 15

์ถœ๋ ฅ - ์ฒซ ์ค„์— ์ตœ๋Œ€ ๋งค์ถœ์•ก์„ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 56

 

 

โ€‹

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {
	public int solution(int n, int k, int[] arr) {
		int answer = 0, sum = 0;
		
		for(int i = 0; i < k; i++) sum += arr[i]; //์ฒซ๋ฒˆ์งธ window
		answer = sum;
		for(int i = k; i < n; i++) {
			sum += arr[i] - arr[i - k];
			answer = Math.max(answer, sum);
		}
		
        	return answer;
	}
	
	public static void main(String[] args){
		Main main  = new Main();
		Scanner sc =new Scanner(System.in);
		
		int n = sc.nextInt();
		int k = sc.nextInt();

		int[] arr = new int[n];
		for(int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		
		System.out.println(main.solution(n, k, arr));
		
		sc.close();
		return ;
	}
}

 

 

 

Comments