Post

๐Ÿน ์—ฐ์†ํ•ฉ 2

1. ๋ฌธ์ œ ๋งํฌ

13398๋ฒˆ: ์—ฐ์†ํ•ฉ 2


2. ์ฝ”๋“œ

Python3 42828KB 204ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
INF = int(1e9)

n = int(input())
numbers = list(map(int, input().split()))
dp = [[0] * 2 for _ in range(n)]
dp[0][0] = numbers[0]
dp[0][1] = numbers[0]

for i in range(1, n):
    # ์ˆซ์ž๋ฅผ ์ œ์™ธํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ
    dp[i][0] = max(dp[i-1][0] + numbers[i], numbers[i])
    # ํ•˜๋‚˜์˜ ์ˆซ์ž๋ฅผ ์ œ์™ธํ•  ๊ฒฝ์šฐ
    dp[i][1] = max(dp[i-1][0], dp[i-1][1] + numbers[i])

result = -INF
for d in dp:
    result = max(result, max(d))
print(result)


3. ํ•ด์„ค

dp ํ…Œ์ด๋ธ”์„ ์—ฐ์†ํ•ฉ์—์„œ ํ•˜๋‚˜์˜ ์ˆซ์ž๋ฅผ ์ œ์™ธํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ โ€˜0โ€™๊ณผ ์ œ์™ธํ•œ ๊ฒฝ์šฐ โ€˜1โ€™์„ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ด์ฐจ์› ๋ฐฐ์—ด๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.

์ˆซ์ž ํ•œ ๊ฐœ ์ด์ƒ์€ ๋ฌด์กฐ๊ฑด ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋ฏ€๋กœ dp[0]์˜ ์‹œ์ž‘์„ ๋‘ ์ผ€์ด์Šค ๋ชจ๋‘ ์ˆ˜์—ด์˜ ๊ฐ€์žฅ ์ฒซ ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.

  • ์ˆซ์ž๊ฐ€ ์ œ์™ธ๋˜์ง€ ์•Š์€ ์—ฐ์†ํ•ฉ์˜ ์ตœ๋Œ“๊ฐ’ dp[i][0]

    (์ด์ „๊นŒ์ง€ ํ•ฉํ•ด์˜จ ์ˆซ์ž + ํ˜„์žฌ ๋ณธ์ธ์˜ ๊ฐ’)๊ณผ (ํ˜„์žฌ ๋ณธ์ธ์˜ ๊ฐ’)์„ ๋น„๊ตํ•ด๋ดค์„ ๋•Œ (ํ˜„์žฌ ๋ณธ์ธ์˜ ๊ฐ’)์ด ๋” ํฌ๋‹ค๋ฉด ์ด์ „ ํ•ฉ์„ ์ถ”๊ฐ€ํ•ด์ค„ ํ•„์š”๊ฐ€ ์—†๋‹ค.

    dp[i-1] + numbers[i] (์ด์ „๊นŒ์ง€ ํ•ฉํ•ด์˜จ ์ˆซ์ž + ํ˜„์žฌ ๋ณธ์ธ์˜ ๊ฐ’) / numbers[i] (ํ˜„์žฌ ๋ณธ์ธ์˜ ๊ฐ’)

    โ†’ dp[i][0] = max(dp[i-1][0] + numbers[i], numbers[i])

  • ์ˆซ์ž๊ฐ€ ์ œ์™ธ๋˜์—ˆ์„ ๋•Œ ์—ฐ์†ํ•ฉ์˜ ์ตœ๋Œ“๊ฐ’ dp[i][1]

    dp[i][1]์€ ํ˜„์žฌ๊นŒ์ง€ ์ˆซ์ž ํ•˜๋‚˜๋Š” ๋ฌด์กฐ๊ฑด ์ œ์™ธ๋œ ์ƒํƒœ๋ฅผ ์˜๋ฏธํ•œ๋‹ค.

    ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ ์ค‘ ํฐ ๊ฒฝ์šฐ๋ฅผ ๊ณ ๋ฅด๋ฉด ๋œ๋‹ค.

    1. ํ˜„์žฌ ์ˆ˜๊นŒ์ง€๋Š” ํ•œ ๋ฒˆ๋„ ์ œ์™ธํ•˜์ง€ ์•Š์•˜๊ณ , ํ˜„์žฌ ๊ฐ’์„ ์ œ์™ธํ•  ๊ฒฝ์šฐ โ†’ dp[i-1][0]
    2. ์ด๋ฏธ ์•ž์—์„œ ์ œ์™ธํ•œ ๊ฒฝ์šฐ์— ํ˜„์žฌ ๊ฐ’์„ ๋”ํ•˜๋Š” ๊ฒฝ์šฐ โ†’ dp[i-1][1] + numbers[i]

    โ†’ dp[i][1] = max(dp[i-1][0], dp[i-1][1] + numbers[i]

This post is licensed under CC BY 4.0 by the author.