huequad / swift-algorithm

1 stars 0 forks source link

1932. 정수 삼각형 #15

Closed zekexros closed 3 years ago

zekexros commented 3 years ago

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

zekexros commented 3 years ago

https://github.com/zeke-iOS/AlgorithmPractice/blob/main/BOJ/BOJ-1932(정수삼각형).swift

ghis22130 commented 3 years ago

https://ghis22130.github.io/2021-07-20-%EB%B0%B1%EC%A4%80_%EC%A0%95%EC%88%98-%EC%82%BC%EA%B0%81%ED%98%95(1932)/

lenaios commented 3 years ago

삼각형의 가장자리를 제외하고, 합이 더 큰 값(max sum)을 저장한다.

import Foundation

let n = readLine()!
var array = [[Int]]()
for _ in 0..<Int(n)! {
    let str = readLine()!
    let arr = str.components(separatedBy: " ")
    array.append(arr.map{ Int($0)! })
}

for i in 1..<array.count {
    for j in 0..<array[i].count {
        if j == 0 { // left
            array[i][j] = array[i][j] + array[i - 1][j]
        } else if j == array[i].count - 1 { // right
            array[i][j] = array[i][j] + array[i - 1][j - 1]
        } else {
            array[i][j] = array[i][j] + max(array[i - 1][j - 1], array[i - 1][j])
        }
    }
}

print(array[array.count - 1].max()!)