문제
https://school.programmers.co.kr/learn/courses/30/lessons/43238
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드
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 cnt=0;
let mid = Math.floor((left+right)/2);
for(time of times){
cnt+=Math.floor(mid/time);
if(cnt>=n){
answer=Math.min(answer,mid);
break;
}
}
if(cnt>=n) right=mid-1;
else left=mid+1;
}
return answer;
}
정리
이분탐색을 하기 위해서는 배열들이 정렬되어 있어야 한다.
times.sort((a,b)=>a-b);
mid값은 소수점을 갖지 않기 위해 Math.floor()를 해준다.
let mid = Math.floor((left+right)/2);
n과 가장 가까운 최솟값 cnt를 찾기 위해 다음과 같이 구현한다.
if(cnt>=n) right=mid-1;
else left=mid+1;
참조
'Programmers' 카테고리의 다른 글
| [프로그래머스] 숫자 문자열과 영단어 (JS) - replaceAll (0) | 2023.11.19 |
|---|---|
| [프로그래머스] 거리두기 확인하기 (JS) - DFS, 2차원 배열 잘 선언하기 (1) | 2023.11.19 |
| [프로그래머스] 네트워크 (JS) - DFS (0) | 2023.11.17 |
| [프로그래머스] 타겟 넘버 (JS) - DFS (0) | 2023.11.17 |
| [프로그래머스] 카펫 (JS) - 완전탐색, 이차 방정식 (0) | 2023.11.15 |