이분탐색 유형.
모든 사람들이 심사 받는 게 판단 조건이다. 이중에서 심사 시간을 줄이는 게 목적이므로, cnt 변수를 통해 심사 받은 사람의 숫자를 센다.
그리고 모두가 심사를 받은 시점(cnt가 n보다 크거나 같아지는 시점)에 mid와 answer를 비교해 최소값을 업데이트해나간다.
현재 mid 값으로 모든 사람을 심사할 수 있다면(cnt>=n), right 값을 mid-1 값으로 당겨서(범위를 좁혀서) 더 적은 시간으로 심사할 수 있는지 판단한다.
반대로, 현재 mid 값으로 모든 사람을 심사할 수 없다면, 보다 많은 시간이 필요하다는 의미이므로 left 값을 mid+1로 당긴다.
function solution(n, times) {
times.sort((a,b) => a-b)
let left = 1
let right = n * times[times.length -1]
let answer = right // 최대값으로 설정하고 시작
while(left <= right){
let mid = Math.floor((left + right) / 2)
let cnt = 0
times.forEach(value => {
cnt += Math.floor(mid / value) // 검사관 한 명이 최대 몇명까지 검사할 수 있는지
if(cnt >= n) {
answer = Math.min(mid, answer) // 최소값으로 업데이트
return
}
})
if (cnt >= n) right = mid - 1
else left = mid + 1
}
return answer
}
console.log(solution(6, [7, 10])) // 28
위 코드를 축약하면 아래와 같다.
function solution(n, times) {
let min=0
let max= n * Math.max.apply(null, times)
while(min<=max){
let mid = Math.floor((min+max)/2)
let maxInMid = times.reduce((acc,cur) => acc += Math.floor(mid/cur), 0)
if(n <= maxInMid) max = mid - 1
else min = mid + 1
}
return min
}