리트코드/midium
[리트코드] 1870. Minimum Speed to Arrive on Time - js (이진탐색)
bbeyak
2023. 8. 19. 12:40
반응형
1. 문제
https://leetcode.com/problems/minimum-speed-to-arrive-on-time/
Minimum Speed to Arrive on Time - LeetCode
Can you solve this real interview question? Minimum Speed to Arrive on Time - You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. Yo
leetcode.com
2. 코드
/**
* @param {number[]} dist
* @param {number} hour
* @return {number}
*/
var minSpeedOnTime = function(dist, hour) {
// hour 안에 도착할 수 있는지 여부 판단
function canReachOnTime(speed) {
// 무조건 한 기차역에서 정수단위로 시간 보내고 다음 기차역으로 넘어가야하므로
// 마지막 역 제외하고는 전부 Math.ceil 처리
let total_time = dist.slice(0, -1)
.reduce((acc, d) => acc + Math.ceil(d / speed), 0) + dist[dist.length - 1] / speed;
return total_time <= hour;
}
let left = 1, right = 10 ** 7;
while (left < right) {
let mid = Math.floor((left + right) / 2);
if (canReachOnTime(mid)) { // 속도의 최소값을 반환해야하므로 더 작은 값 찾아보기
right = mid;
} else {
left = mid + 1;
}
}
if (canReachOnTime(left)) {
return left; // 최소값을 반환해야하기 떄문에 left 리턴
} else {
return -1;
}
};
시작과 끝 값이 주어지고 그 중 가장 최선의 선택을 해야할 때는 무조건 이진 탐색 활용하기... 아직도 이진 탐색이 어렵다ㅠㅠ 문제 보면 얘가 이진 탐색 문제구나! 가 떠오르지 않는게 문제...
반응형