ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90

๐Ÿšฉ DP

 

thinking

์ „ํ˜•์ ์ธ DP ๋ฌธ์ œ์ด๋‹ค.

๋ฌด์กฐ๊ฑด ๋งˆ์ง€๋ง‰ ๊ณ„๋‹จ์„ ๋ฐŸ์•„์•ผ ํ•˜๋ฏ€๋กœ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋’ค์ง‘์–ด 0๋ฒˆ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์คฌ๋‹ค.

์—ฐ์†๋œ ์„ธ ๊ฐœ์˜ ๊ณ„๋‹จ์„ ๋ฐŸ์œผ๋ฉด ์•ˆ๋˜๊ธฐ ๋•Œ๋ฌธ์— dp[i-1]+s[i] ๋กœ ํ•˜์ง€ ์•Š๊ณ  dp[i-3]+s[i-1]+s[i] ๋กœ ์„ค์ •ํ•ด์คฌ๋‹ค.

 

๋Ÿฐํƒ€์ž„์—๋Ÿฌ (IndexError) ์ฃผ์˜ !

์ฒซ๊ณ„๋‹จ๊ณผ ๋‘๋ฒˆ์งธ ๊ณ„๋‹จ์„ ์•„๋ž˜์ฒ˜๋Ÿผ ์„ค์ •ํ–ˆ๋”๋‹ˆ ์ธ๋ฑ์Šค ์—๋Ÿฌ๊ฐ€ ๋‚ฌ๋‹ค. range์˜ ๋ฒ”์œ„๊ฐ€ 3 ์ดํ•˜์ผ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ํŒจ์“ฐ์ฝ”๋“œ์ฒ˜๋Ÿผ ์ž‘์„ฑํ•ด์•ผ ํ•œ๋‹ค.

# Index Error ๋‚œ ๋ถ€๋ถ„
dp = [0]*N
dp[0] = s[0]
dp[1] = s[0]+s[1]
dp[2] = s[0]+s[2]

for i in range(3, N):
    dp[i] = max(dp[i-2]+s[i], dp[i-3]+s[i-1]+s[i])

 

์ฝ”๋“œ

N = int(input())
s = [int(input()) for _ in range(N)]
s.reverse()

dp = [0]*N
dp[0] = s[0]

for i in range(1, N):
    if i < 3:
        dp[i] = s[0] + s[i]
    else:
        dp[i] = max(dp[i-2]+s[i], dp[i-3]+s[i-1]+s[i])

print(max(dp[N-2], dp[N-1]))

 

๋Œ“๊ธ€