Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 1912๋ฒˆ - ์—ฐ์†ํ•ฉ (dp max ๊ฐ’ ๊ตฌํ•˜๊ธฐ!)

๊ฐ์ž ๐Ÿฅ” 2022. 3. 16. 15:55
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ๋งํฌ

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

 

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

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

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด idea

์•ž์—์„œ ํ’€๋˜ dp ๋ฌธ์ œ์™€ ๋‹ค๋ฅผ ๊ฒƒ ์—†๋Š” ๋ฌธ์ œ! ์•ž์—์„œ๋ถ€ํ„ฐ ๋”ํ•ด์ฃผ๊ณ  max๊ฐ’์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ๋ฉด ๋ผ. ์™œ๋ƒ๋ฉด!! ์–ด์ฐจํ”ผ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ์ฐพ๋Š”๊ฑฐ๋ผ ๊ณ„์™ max ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธ ๋˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

์†Œ์Šค์ฝ”๋“œ

let n = Int(String(readLine()!))!
let arr = readLine()!.split(separator: " ").map{Int(String($0))!}
var dp = Array(repeating: -1001, count: 100001)

dp[0] = arr[0]

for i in 1..<n{
    dp[i] = max(arr[i],dp[i - 1] + arr[i])
}
print(dp.max()!)

 

๋ฐ˜์‘ํ˜•