๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Baekjoon][๋ฌธ์ž์—ด] 2559 ์ˆ˜์—ด (feat. prefix sum)

ibelieveinme 2024. 4. 13. 15:46
728x90

๋ฌธ์ œ

https://www.acmicpc.net/problem/2559

 

2559๋ฒˆ: ์ˆ˜์—ด

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

www.acmicpc.net

๋งค์ผ ์ธก์ •ํ•œ ์˜จ๋„๊ฐ€ ์ •์ˆ˜์˜ ์ˆ˜์—ด๋กœ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์—ฐ์†์ ์ธ ๋ฉฐ์น  ๋™์•ˆ์˜ ์˜จ๋„์˜ ํ•ฉ์ด ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๊ณ„์‚ฐํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ

 

์กฐ๊ฑด

N์€ 2 ์ด์ƒ 100,000 ์ดํ•˜

์ฃผ์–ด์ง€๋Š” ์ˆ˜๋“ค์€ ๋ชจ๋‘ -100 ์ด์ƒ 100 ์ดํ•˜

 

 

 

์˜ˆ์ œ ๋ฌธ์ œ/๋‹ต

10 2
3 -2 -4 -9 0 3 7 13 8 -3

10๊ฐœ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๊ณ , 2์ผ์น˜๋ฅผ ์—ฐ์†์ ์œผ๋กœ ๋”ํ–ˆ์„ ๋•Œ ๊ฐ– ๊ฐ’,

 

=> ์ •๋‹ต์€ 21

 

 

 

ํ•ด๊ฒฐ๋ฐฉ๋ฒ•

์ฒจ์— ๊ทœ์น™ ์ฐพ์•„์„œ ํ•˜๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ, ์ธ๋ฑ์Šค๋ฅผ ์ž˜๋ชป ๊ณ„์‚ฐํ–ˆ๋Š”์ง€ ์ด์ƒํ•œ ๊ฐ’์ด ๋‚˜์™”๋‹ค. ๊ฐ•์˜ ๋‹ต์•ˆ ๊ฐ•์ด๋ž‘ ๋ˆ„์ ํ•ฉ ๊ฐœ๋… ์ •๋ฆฌ ์˜์ƒ๋ณด๊ณ  ํ’€์—ˆ๋‹ค.

 

 

 

์ฝ”๋“œ

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

int main() {

	int totalDay, continueDay, max = INT_MIN;

	cin >> totalDay >> continueDay;

	vector<int> temperates(totalDay + 1, 0);
	vector<int> psum(totalDay + 1, 0);

	for (int i = 1; i <= totalDay; i++) {
		cin >> temperates[i];
		temperates[i] += temperates[i - 1]; //prefix sum
	}

	for (int i = continueDay; i <= totalDay; i++) {
		int sum = temperates[i] - temperates[i - continueDay];
		if (sum > max) max = sum;
	}

	cout << max << "\n";

	return 0;
}

 

๋‘๋ฒˆ์งธ for ๋ฌธ์—์„œ i ์‹œ์ž‘์ด continueDay ์ด๋‹ค. ๊ธฐ์–ตํ•˜์ž.

 

 

 

 

๋ˆ„์ ํ•ฉ ์ฐธ๊ณ  ์ž๋ฃŒ

 

[10์ฃผ ์™„์„ฑ C++ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ] ๋ˆ„์ ํ•ฉ, Prefix Sum

* ๋ˆ„์ ํ•ฉ: ์–ด๋–ค ๋ฐฐ์—ด์˜ ์•ž ์š”์†Œ๋ถ€ํ„ฐ ๋ˆ„์ ๋œ ํ•ฉ์„ ์ €์žฅํ•œ ๋ฐฐ์—ด. ์•ž์—์„œ๋ถ€ํ„ฐ ๋”ํ•˜๋Š” prefix sum๊ณผ ๋’ค์—์„œ ๋ถ€ํ„ฐ ๋”ํ•˜๋Š” suffix sum ์ด ์žˆ๋‹ค. ๋ฐฐ์—ด์˜ ๊ฐ’์ด ๋ณ€ํ•˜์ง€ ์•Š๋Š” ์ •์  ๋ณ€์ˆ˜์—๋งŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. * ๋ˆ„์ 

i-believe-in-me.tistory.com

 

 

728x90