[Algorithm] ๐Ÿท๋ฐฑ์ค€ 2156 ํฌ๋„์ฃผ ์‹œ์‹

0. ๋ฌธ์ œ

ํšจ์ฃผ๋Š” ํฌ๋„์ฃผ ์‹œ์‹ํšŒ์— ๊ฐ”๋‹ค. ๊ทธ ๊ณณ์— ๊ฐ”๋”๋‹ˆ, ํ…Œ์ด๋ธ” ์œ„์— ๋‹ค์–‘ํ•œ ํฌ๋„์ฃผ๊ฐ€ ๋“ค์–ด์žˆ๋Š” ํฌ๋„์ฃผ ์ž”์ด ์ผ๋ ฌ๋กœ ๋†“์—ฌ ์žˆ์—ˆ๋‹ค. ํšจ์ฃผ๋Š” ํฌ๋„์ฃผ ์‹œ์‹์„ ํ•˜๋ ค๊ณ  ํ•˜๋Š”๋ฐ, ์—ฌ๊ธฐ์—๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋‘ ๊ฐ€์ง€ ๊ทœ์น™์ด ์žˆ๋‹ค.

1.ํฌ๋„์ฃผ ์ž”์„ ์„ ํƒํ•˜๋ฉด ๊ทธ ์ž”์— ๋“ค์–ด์žˆ๋Š” ํฌ๋„์ฃผ๋Š” ๋ชจ๋‘ ๋งˆ์…”์•ผ ํ•˜๊ณ , ๋งˆ์‹  ํ›„์—๋Š” ์›๋ž˜ ์œ„์น˜์— ๋‹ค์‹œ ๋†“์•„์•ผ ํ•œ๋‹ค.
2.์—ฐ์†์œผ๋กœ ๋†“์—ฌ ์žˆ๋Š” 3์ž”์„ ๋ชจ๋‘ ๋งˆ์‹ค ์ˆ˜๋Š” ์—†๋‹ค.

ํšจ์ฃผ๋Š” ๋  ์ˆ˜ ์žˆ๋Š” ๋Œ€๋กœ ๋งŽ์€ ์–‘์˜ ํฌ๋„์ฃผ๋ฅผ ๋ง›๋ณด๊ธฐ ์œ„ํ•ด์„œ ์–ด๋–ค ํฌ๋„์ฃผ ์ž”์„ ์„ ํƒํ•ด์•ผ ํ• ์ง€ ๊ณ ๋ฏผํ•˜๊ณ  ์žˆ๋‹ค. 1๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ๋ฒˆํ˜ธ๊ฐ€ ๋ถ™์–ด ์žˆ๋Š” n๊ฐœ์˜ ํฌ๋„์ฃผ ์ž”์ด ์ˆœ์„œ๋Œ€๋กœ ํ…Œ์ด๋ธ” ์œ„์— ๋†“์—ฌ ์žˆ๊ณ , ๊ฐ ํฌ๋„์ฃผ ์ž”์— ๋“ค์–ด์žˆ๋Š” ํฌ๋„์ฃผ์˜ ์–‘์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ํšจ์ฃผ๋ฅผ ๋„์™€ ๊ฐ€์žฅ ๋งŽ์€ ์–‘์˜ ํฌ๋„์ฃผ๋ฅผ ๋งˆ์‹ค ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

์˜ˆ๋ฅผ ๋“ค์–ด 6๊ฐœ์˜ ํฌ๋„์ฃผ ์ž”์ด ์žˆ๊ณ , ๊ฐ๊ฐ์˜ ์ž”์— ์ˆœ์„œ๋Œ€๋กœ 6, 10, 13, 9, 8, 1 ๋งŒํผ์˜ ํฌ๋„์ฃผ๊ฐ€ ๋“ค์–ด ์žˆ์„ ๋•Œ, ์ฒซ ๋ฒˆ์งธ, ๋‘ ๋ฒˆ์งธ, ๋„ค ๋ฒˆ์งธ, ๋‹ค์„ฏ ๋ฒˆ์งธ ํฌ๋„์ฃผ ์ž”์„ ์„ ํƒํ•˜๋ฉด ์ด ํฌ๋„์ฃผ ์–‘์ด 33์œผ๋กœ ์ตœ๋Œ€๋กœ ๋งˆ์‹ค ์ˆ˜ ์žˆ๋‹ค.

์ž…๋ ฅ
์ฒซ์งธ ์ค„์— ํฌ๋„์ฃผ ์ž”์˜ ๊ฐœ์ˆ˜ n์ด ์ฃผ์–ด์ง„๋‹ค. (1โ‰คnโ‰ค10,000) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ n+1๋ฒˆ์งธ ์ค„๊นŒ์ง€ ํฌ๋„์ฃผ ์ž”์— ๋“ค์–ด์žˆ๋Š” ํฌ๋„์ฃผ์˜ ์–‘์ด ์ˆœ์„œ๋Œ€๋กœ ์ฃผ์–ด์ง„๋‹ค. ํฌ๋„์ฃผ์˜ ์–‘์€ 1,000 ์ดํ•˜์˜ ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜์ด๋‹ค.

์ถœ๋ ฅ
์ฒซ์งธ ์ค„์— ์ตœ๋Œ€๋กœ ๋งˆ์‹ค ์ˆ˜ ์žˆ๋Š” ํฌ๋„์ฃผ์˜ ์–‘์„ ์ถœ๋ ฅํ•œ๋‹ค.

1. ์•„์ด๋””์–ด

์ด 3๊ฐ€์ง€๋กœ ๋‚˜๋ˆ„์–ด์„œ ๊ณ„์‚ฐ
1) ํ˜„์žฌ ํฌ๋„์ฃผ X
2) ํ˜„์žฌ ํฌ๋„์ฃผ O, ์ด์ „ ํฌ๋„์ฃผ X
3) ํ˜„์žฌ ํฌ๋„์ฃผ O, ์ด์ „ ํฌ๋„์ฃผ O

  • ์—ฐ์†ํ•ด์„œ 2๋ฒˆ๊นŒ์ง€ ๋งˆ์‹ค ์ˆ˜ ์žˆ์Œ *

2. ํ•ต์‹ฌ ํ’€์ด

1) ํ˜„์žฌ ํฌ๋„์ฃผ X

dp[i-1]

2) ํ˜„์žฌ ํฌ๋„์ฃผ O, ์ด์ „ ํฌ๋„์ฃผ X

dp[i-2]+p[i]

3) ํ˜„์žฌ ํฌ๋„์ฃผ O, ์ด์ „ ํฌ๋„์ฃผ O

dp[i-3] + p[i] + p[i-2]

3. ์ฝ”๋“œ

import java.util.Scanner;

public class DP_3 {
	static int p[];
	static int dp[];
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		p = new int[n+10];
		dp = new int[n+10];
		
		for(int i=1; i<=n; i++)
			p[i] = sc.nextInt();
		
		dp[1] = p[1];
		dp[2] = p[1]+p[2];
		
		System.out.println(maxWine(n));

	}
	
	static int maxWine(int n) {
		for(int i=3; i<=n; i++) {
			int ret = 0;
			ret = Math.max(p[i]+dp[i-2], dp[i-1]);
			ret = Math.max(ret, dp[i-3]+p[i-1]+p[i]);
			dp[i] = ret;
		}
		
		return dp[n];
	}

}

4. ๊ฒฐ๊ณผ


์„ฑ๊ณต~

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ