๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ์—ฐ์†ํ•ฉ BOJ #1912

by seolhee2750 2022. 1. 31.
๋ฌธ์ œ

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

 

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

์ฒซ์งธ ์ค„์— ์ •์ˆ˜ n(1 ≤ n ≤ 100,000)์ด ์ฃผ์–ด์ง€๊ณ  ๋‘˜์งธ ์ค„์—๋Š” n๊ฐœ์˜ ์ •์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆ˜์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ์ˆ˜๋Š” -1,000๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 1,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜์ด๋‹ค.

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import sys
sys.setrecursionlimit(1000000)

n = int(input())
nums = list(map(int, input().split()))
sums = [nums[0]]

for i in range(1, n):
    if nums[i] < sums[-1] + nums[i]:
        sums.append(sums[-1] + nums[i])
    else:
        sums.append(nums[i])

print(max(sums))

๐Ÿ‘‰ DP ๋ฌธ์ œ๋กœ, ์—ฐ์†๋˜๋Š” ์ˆ˜๋“ค์˜ ํ•ฉ์˜ ์ตœ๋Œ€๋ฅผ ์ˆœ์„œ๋Œ€๋กœ ๋ˆ„์ ํ•ด์ฃผ๋Š” ๊ฒƒ์ด ํฌ์ธํŠธ !

  • ์ž…๋ ฅ๋ฐ›์€ nums ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœ์ฐจ์ ์œผ๋กœ ๋Œ๋ฉฐ (ํ˜„์žฌ ๊ฐ’ + ๋ˆ„์  ํ•ฉ)๊ณผ (ํ˜„์žฌ ๊ฐ’)์„ ๋น„๊ตํ–ˆ๋‹ค.
  • (ํ˜„์žฌ ๊ฐ’)์ด ๋” ํด ๊ฒฝ์šฐ ์•ž์—์„œ ์—ฐ์†๋œ ์ˆ˜๋“ค์˜ ํ•ฉ์„ ๋”ํ•˜๋Š” ๊ฒƒ์ด ์†ํ•ด์ด๋ฏ€๋กœ
    ํ˜„์žฌ ๊ฐ’์„ ๊ทธ๋Œ€๋กœ sum ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ํ–ˆ๋‹ค.
  • (ํ˜„์žฌ ๊ฐ’ + ๋ˆ„์  ํ•ฉ)์ด ๋” ํด ๊ฒฝ์šฐ, ๋ˆ„์ ํ•ด์˜จ ํ•ฉ์„ ๋”ํ•˜๋Š” ๊ฒƒ์ด ์ด๋“์ด๋ฏ€๋กœ
    ํ˜„์žฌ๊ฐ’์— ๋ˆ„์ ํ•œ ๊ฐ’์„ ๋”ํ•œ ๊ฐ’์„ sums ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ํ–ˆ๋‹ค.
  • ์œ„์™€ ๊ฐ™์€ ์‹คํ–‰์„ ํ†ตํ•ด ์•ž์˜ ์ˆ˜์— ์—ฐ์†ํ•˜์—ฌ ๊ฐ’์„ ๋”ํ•  ๊ฒƒ์ธ์ง€,
    ์•„๋‹ˆ๋ฉด ์ƒˆ๋กœ์šด ์—ฐ์† ํ•ฉ์„ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด ๋งž๋Š”์ง€ ํŒ๋ณ„ํ•ด ์ฃผ๋ฉด ๋œ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์ฃผ์–ด์ง„ ์˜ˆ์‹œ๋ฅผ ๋ถ„์„ํ•ด๋ณด๋ฉด ์‰ฝ๊ฒŒ ํ’€์ด ๋ฐฉ๋ฒ•์„ ์•Œ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€๋‹ค.

๋Œ“๊ธ€