LeetCode 1870. Minimum Speed to Arrive on Time
ποΈ Daily LeetCoding Challenge July, Day 26
(23.07.26) μΌμμ… bruteforce
λ‘ νμλλ TLE
(Time Limit Exceeded)… κ·Έλμ binary-search
λ‘ νμ΄λ μ¬μ ν TLE
. ν… C++λ Javaλ μλ§ ν΅κ³Όνλκ±° κ°μλ° ‘[1,1,10000000]’ κ°μ μμκ° λμ€λ©΄ time complexityκ° $ O(10^7) $ μ΄ λμ΄λ²λ €μ νμ΄μ¬μ μλΉ
- μ€ν¨!λ₯Ό μΈμΉλ€γ
γ
binary search μ΄λΆ νμ νμ΄
μλ μ½λμ²λΌ κΉλνκ² νμλλ°λ TLE μ€λ₯κ° λ΄λ€. μ무λλ ν¨μ λ°λ‘ νλ κ² μ‘°μ°¨λ μκ° λ³΅μ‘λμ κΈ°μ¬νλλ―, νλ²μ μ½λλ₯Ό μμ±νλ μμΌλ‘ λ€μ μ¬κ΅¬μ±ν΄λ³΄κΈ°λ‘ νλ€.
class Solution:
def minSpeedOnTime(self, dist: List[int], hour: float) -> int:
# binary-search
low,top = 1,10**7
while low <= top:
mid = (low+top)//2
if self.check(dist, hour, mid):
low = mid -1
else:
high = mid+1
return mid if self.check(dist, hour, mid) else -1
def check(self, dist, hour, speed):
time = 0
for num in dist[:-1]:
time += math.ceil(num/speed)
time += dist[-1]/speed
return time <= hour
ν° μ°¨μ΄λ μλκ±° κ°μ§λ§, λ€μκ³Ό κ°μ΄ λ°κΏλ³΄λ ν΅κ³Όλ λλλΌγ γ νμ΄μ¬ TLE μκΎΈ κ±Έλ €μ κ±°μ¬λ¦¬λ€…γ γ γ μκ³ λ¦¬μ¦μ λ§κ² μ§ κ±° κ°μλ° μκ°μ΄κ³Ό 걸리면 κΈ°λΆλκ° λ§€μ° μ’μ§ λͺ»νλ€.
import math
class Solution:
def minSpeedOnTime(self, dist: List[int], hour: float) -> int:
def can_reach(speed):
temp = 0
for i in range(len(dist) - 1):
temp += math.ceil(dist[i] / speed)
if temp > hour:
return False
return (temp + (dist[-1] / speed)) <= hour
low = 1
top = 10**7
max_speed = -1
while low <= top:
mid = (low + top) // 2
if can_reach(mid):
max_speed = mid
top = mid - 1
else:
low = mid + 1
return max_speed