→ Problems
[Algorithm] 백준 - 16198번 에너지 모으기 (Swift)
Swift librarian
2024. 5. 31. 21:48
문제 소개

문제 풀이
깊이우선탐색(dfs)을 활용하여 최댓값을 출력하였다.
import Foundation
let n = Int(readLine()!)!
let weights = readLine()!.split(separator: " ").map { Int($0)! }
var maxValue = 0
func dfs(_ current: Int, _ weights: [Int]) {
if weights.count == 2 {
maxValue = max(maxValue, current)
}
for i in 1..<weights.count-1 {
var newWeights = weights
newWeights.remove(at: i)
dfs(current + weights[i-1] * weights[i+1], newWeights)
}
}
dfs(0, weights)
print(maxValue)