๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90
๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

2559๋ฒˆ: ์ˆ˜์—ด

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

www.acmicpc.net

 

๐Ÿง‘‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

๋„คํŠธ์›Œํฌ์—์„œ TCP ํ”„๋กœํ† ์ฝœ์„ ๊ณต๋ถ€ํ•  ๋•Œ ๋ดค์—ˆ๋˜ ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ(Sliding window) ๊ฐœ๋…์„ ์ ์šฉํ•˜์—ฌ ํ’€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  1. ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ๊ฐ ์ˆซ์ž๋“ค์„ ๋ฐฐ์—ด(arr)์— ์ €์žฅํ•˜๋˜, [0, K - 1]๊นŒ์ง€์˜ ํ•ฉ๊ณ„๋ฅผ ๋ณ„๋„์˜ ๋ณ€์ˆ˜(sum)์— ์ €์žฅํ•ด๋‘ก๋‹ˆ๋‹ค.
  2. int start = 0, last = K๋กœ ์ธ๋ฑ์Šค ๋ณ€์ˆ˜๋ฅผ ๋‘ก๋‹ˆ๋‹ค.
  3. ์ •๋‹ต ๋ณ€์ˆ˜(maxSum)์„ 1๋ฒˆ์—์„œ ๊ตฌํ•œ sum ๋ณ€์ˆ˜ ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค.
  4. last < K๊ฐ€ ๋งŒ์กฑํ•  ๋•Œ, ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.
    • sum -= arr[start++];
    • sum += arr[last++];
    • maxSum = max(maxSum, sum);

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <iostream>
#include <vector>
using namespace std;

int main()
{
	ios::sync_with_stdio(false);
	cout.tie(NULL); cin.tie(NULL);

	int N, K;
	cin >> N >> K;

	// 1. [0, K - 1]๊นŒ์ง€ ํ•ฉ๊ณ„ ๊ตฌํ•˜๊ธฐ
	int sum = 0;
	vector<int> sequence(N);
	for (int i = 0; i < N; i++)
	{
		cin >> sequence[i];

		if (i < K)
			sum += sequence[i];
	}

	// 2. start, last ์ธ๋ฑ์Šค๋ฅผ ํ†ตํ•ด, ํ•œ ์นธ์”ฉ ์ „์ง„
	int maxSum = sum;
	for (int start = 0, last = K; last < N; start++, last++)
	{
		sum -= sequence[start];
		sum += sequence[last];

		maxSum = max(maxSum, sum);
	}

	cout << maxSum;
	return 0;
}

 

728x90
๋ฐ˜์‘ํ˜•