본문 바로가기

알고리즘

[그리디] 백준 9237 문제 : 이장님 나무 심기 - 스위프트

문제 : https://www.acmicpc.net/problem/9237

 

9237번: 이장님 초대

입력은 두 줄로 이루어져 있다. 첫째 줄에는 묘목의 수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄에는 각 나무가 다 자라는데 며칠이 걸리는지를 나타낸 ti가 주어진다. (1 ≤ ti ≤ 1,000,000)

www.acmicpc.net

 

그때 그때 자라는데 가장 오래 걸리는 씨앗을 찾아서 먼저 심기 : 그리디

//  1일 2일 3일 4일
//+ 4,  3,  3, 2
//----------------
//  5   5   6  6
// Max 값 = 6 + 1
func solution() -> Int {
    _ = Int(readLine()!)!
    let inputSecond = readLine()?.components(separatedBy: " ").map{Int($0)!}
    var max = 0
    let result = inputSecond!.sorted(by: >)
    
    for index in 0..<inputSecond!.count {
        let tempMax = result[index] + (index+1)
        if max < tempMax {
            max = tempMax
        }
    }
    return max + 1
}

print(solution())

 

반응형