-
[프로그래머스 - Swift] 탐욕법(Greedy) - 체육복iOS/CodingTest 2020. 12. 29. 16:34
programmers.co.kr/learn/courses/30/lessons/42862
코딩테스트 연습 - 체육복
점심시간에 도둑이 들어, 일부 학생이 체육복을 도난당했습니다. 다행히 여벌 체육복이 있는 학생이 이들에게 체육복을 빌려주려 합니다. 학생들의 번호는 체격 순으로 매겨져 있어, 바로 앞번
programmers.co.kr
import Foundation func solution(_ n:Int, _ lost:[Int], _ reserve:[Int]) -> Int { // 체육복 보유 갯수 배열, 도난시 -1 var list = Array(repeating: 0, count: n) // 체육복을 잃어버렸으면 -1 lost.forEach { l in list[l-1] -= 1 } // 여벌 체육복이 있으면 +1 reserve.forEach { r in list[r-1] += 1 } for i in 0..<list.count { if list[i] < 0 { // 체육복을 빌려야하는 학생 if i > 0, list[i-1] == 1 { list[i-1] = 0 list[i] = 0 } else if i < n-1, list[i+1] == 1 { list[i+1] = 0 list[i] = 0 } } } return list.filter { $0 >= 0 }.count }
'iOS > CodingTest' 카테고리의 다른 글
[프로그래머스 - Swift] 깊이/너비 우선 탐색(DFS/BFS) - 타겟 넘버 (0) 2020.12.29