Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: # find smallest k that koko can finish in H hours left = 1 right = max(piles) def can(k): return sum((p-1)//k + 1 for p in piles) <= H while left < right: mid = (left + right) //2 # mid=left<right, left=right if can(mid): right = mid else: left = mid + 1 return right
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def time_used(T): return sum(p//T + (1 if p%T else 0) for p in piles) low = max(sum(piles)//H, 1) if time_used(low) <= H: return low high = max(piles) while low+1 < high: mid = (low + high)//2 if time_used(mid) > H: low = mid else: high = mid return high
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: # Find the first <= in [> > > > > <= <=] n = len(piles) low, high = 1, max(piles) while (low + 1) < high: mid = low + ((high - low) // 2) used_hrs = self.calc_hours(piles, mid) if used_hrs > H: low = mid else: high = mid if self.calc_hours(piles, low) <= H: return low if self.calc_hours(piles, high) <= H: return high @staticmethod def calc_hours(piles, K): return int(sum(((pile - 1) // K + 1) for pile in piles))
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: lo, hi = 1, max(piles) while lo<hi: mid=(lo+hi)//2 cur_cap, num_hrs = 0, 0 for p in piles: cur_cap = p if cur_cap<=mid: num_hrs+=1 else: num_hrs+=(cur_cap//mid)+1 if num_hrs>H: lo=mid+1 else: hi=mid return lo
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def simulate(k): hours = 0 for pile in piles: hours += ceil(pile / k) return hours lower = 1 upper = 1 for pile in piles: upper = max(upper, pile) while lower < upper: midpoint = (upper + lower) // 2 if simulate(midpoint) > H: lower = midpoint + 1 else: upper = midpoint return upper
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def possible(K): return sum(math.ceil(p/ K) for p in piles) <= H N = len(piles) if H == N: return max(piles) sm = sum(piles) lo, hi = int(sm/H)+1, math.ceil(sm/(H-N)) while lo < hi: mi = (lo + hi) // 2 if not possible(mi): lo = mi + 1 else: hi = mi return hi
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: l, h = 1, max(piles) def canFinish(k): hoursTaken = sum([ceil(p / k) for p in piles]) return hoursTaken <= H while l < h: mid = l + (h - l) // 2 if canFinish(mid): h = mid else: l = mid + 1 return l
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: low = 1 high = max(piles) while low < high: mid = (low + high) // 2 if sum(pile // mid + (pile % mid > 0) for pile in piles) > H: low = mid + 1 else: high = mid return low
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def can_eat(x: int, h: int) -> bool: hrs = 0 for p in piles: if p<=x: hrs += 1 else: hrs += (p//x)+1 if hrs > h: return False # print(x, hrs) return True low, high = 1, max(piles) while low<high: mid = low+((high-low)//2) if can_eat(mid, H): high = mid else: low = mid+1 return low
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def count(k): hours = 0 for i in range(len(piles)): hours += (piles[i] + k - 1) // k return hours l = 1 r = 1000000000 while l < r: m = l + (r - l) //2 if count(m) > H: l = m + 1 else: r = m return l
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def possible(K): #check if it is possible for K bananas to be finished in H hours count = 0 for banana in piles: if banana%K==0: count+=banana/K else: count += banana//K+1 if count <= H: return True else: return False left,right = 1,max(piles) while left<=right: mid = (left + right) //2 if possible(mid): right=mid-1 else: left=mid+1 return left
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
#SELF TRY 10/7/2020 class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def eat_speed(K, H): banana_per_hour = 0 for pile in piles: banana_per_hour += pile // K if pile % K != 0: #You can eat all of it banana_per_hour += 1 return banana_per_hour #inclusive left = 1 right = max(piles) while left <= right: K = left + (right - left) // 2 banana_per_hour = eat_speed(K,H) if banana_per_hour <= H: #this is fine right = K - 1 else: #banana_per_hour > H #not possible left = K + 1 return left # class Solution: # def minEatingSpeed(self, piles: List[int], H: int) -> int: # def K_speed(K, piles): # hours_to_eat = 0 # for pile in piles: # hours_to_eat = hours_to_eat + (pile // K) # if pile % K != 0: # hours_to_eat += 1 # # if pile % K == 0: # return hours_to_eat # #two cases # # 1 < H # #2 == H # left = 1 # right = max(piles) # #other way is inclusive ^ # #but left <= right # # and if that's the case right = K - 1 # #So if you do it <= you know that AT that point hours to eat is <= H we know that there's a possibility of our CURRENT K being a solution # #However in this case you need to do a K - 1 because you are trying to find the next smallest for Koko still eating all bananas. # #Because if our RIGHT becomes < our right we are done # while left < right: # K = left + (right - left) // 2 # if K_speed(K, piles) <= H: # right = K # else: # left = K + 1 # # LEFT has passed your RIGHT BOUND # #inclsuvie or exclusive inclsuive w/ one exclusive # #I give you a number that doesn't exist # return left # #BINARY SEARCH # LEFT <= RIGHT: # return LEFT whatever it is your answer #monkey eats bananas #there are N piles of bananas #the i-th pile has piles[i] amount of bananas #The guard have gone and will come back in H hours #She has a bananas eating per hour speed K #Each hour she chosses some banans and eats the K bannas in that pile # 1) #If the pile has less than K bananas she eats all of them #And won't eat anymore bananas during the hour #Monkey eats slow but needs to finish eating all the bananas before the guard comes back #Return the minimum (int) K s.t she can eat all the bananas within H hours. # #K to try to eat all the piles within that hour
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: l = 1 r = max(piles) def findTime(count): hr = 0 for p in piles: hr += (p-1)//count+1 if hr>H: return False return True while l<r: mid = l+(r-l)//2 if findTime(mid): r = mid else: l = mid+1 return l
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def count_hours(k): hours = 0 if k == 1: return sum(piles) for p in piles: hours += p//k if p%k != 0: hours += 1 return hours least = 1 most = max(piles) while least <= most: mid = (most+least)//2 num_hours = count_hours(mid) if num_hours <= H: most = mid -1 else: least = mid + 1 return least
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def K_speed(K, piles): hours_to_eat = 0 for pile in piles: hours_to_eat = hours_to_eat + (pile // K) if pile % K != 0: hours_to_eat += 1 # if pile % K == 0: return hours_to_eat #two cases # 1 < H #2 == H left = 1 right = max(piles) #other way is inclusive ^ #but left <= right # and if that's the case right = K - 1 #So if you do it <= you know that AT that point hours to eat is <= H we know that there's a possibility of our CURRENT K being a solution #However in this case you need to do a K - 1 because you are trying to find the next smallest for Koko still eating all bananas. while left < right: K = left + (right - left) // 2 if K_speed(K, piles) <= H: right = K else: left = K + 1 # LEFT has passed your RIGHT BOUND #inclsuvie or exclusive inclsuive w/ one exclusive #I give you a number that doesn't exist return left # #BINARY SEARCH # LEFT <= RIGHT: # return LEFT whatever it is your answer #monkey eats bananas #there are N piles of bananas #the i-th pile has piles[i] amount of bananas #The guard have gone and will come back in H hours #She has a bananas eating per hour speed K #Each hour she chosses some banans and eats the K bannas in that pile # 1) #If the pile has less than K bananas she eats all of them #And won't eat anymore bananas during the hour #Monkey eats slow but needs to finish eating all the bananas before the guard comes back #Return the minimum (int) K s.t she can eat all the bananas within H hours. # #K to try to eat all the piles within that hour
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: left, right = 1, max(piles) while left < right: mid = left + (right - left) // 2 if self.__getEatHours(piles, mid) <= H: right = mid else: left = mid + 1 return left def __getEatHours(self, piles, speed): hours = 0 for p in piles: hours += p // speed if p % speed != 0: hours += 1 return hours
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: left, right = 1, max(piles) while left <= right: k = left + (right - left) // 2 if self.finish(k, piles) <= H: # count time to eat all bananas at speed K right = k - 1 else: left = k + 1 return left def finish(self, k, piles): res = 0 for pile in piles: res += pile // k if pile % k != 0: res += 1 return res
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: lo, hi = 1, max(piles) while lo <= hi: k = lo + (hi - lo) // 2 if self.finish(k, piles) <= H: # count time to eat all bananas at speed K hi = k - 1 else: lo = k + 1 return lo def finish(self, k, piles): res = 0 for pile in piles: res += pile // k if pile % k != 0: res += 1 return res
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: # wants to eat all bananas within H hours # K - speed at which eat banana # can eat up to pile[i] banana # cannot eat 2 piles in 1 hour # return min K to eat all bananas in H hours def get_hours_needed(piles, K): hours_needed = 0 for pile in piles: hours_needed += pile // K if pile % K != 0: hours_needed += 1 return hours_needed lo = 1 hi = max(piles) while lo < hi: mid = lo + (hi - lo) // 2 if get_hours_needed(piles, mid) > H: lo = mid + 1 else: #hours_needed <= H hi = mid return lo
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: # use binary search to find the correct value maxPile = 0 for i in piles: if i > maxPile: maxPile = i low = 1 high = maxPile minVal = maxPile while low <= high: middle = (low + high) // 2 numHours = 0 for j in piles: numHours += j // middle if j % middle > 0: numHours += 1 if numHours <= H: minVal = middle high = middle - 1 else: low = middle + 1 return minVal
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: l, r = 1, max(piles) while l < r: p = l + (r - l) // 2 if sum(math.ceil(x / p) for x in piles) > H: l = p+1 else: r = p return l
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: n = len(piles) if not n: return -1 def binary_search(l, r): nonlocal piles, H while l < r: mid = (l + r) // 2 if num_hours(mid) <= H: r = mid else: l = mid + 1 return l def num_hours(bananas_per_hour): nonlocal piles res = 0 for i in piles: if bananas_per_hour >= i: res += 1 continue res += (i // bananas_per_hour) res += 1 if i % bananas_per_hour else 0 return res return binary_search(1, max(piles)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def possible(K): return sum(math.ceil(p/K) for p in piles) <= H lo, hi = 1, max(piles) while lo < hi: mid = int(lo + (hi-lo)/2) if not possible(mid): lo = mid+1 else: hi = mid return lo
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def helper(speed): h = 0 for p in piles: h += math.ceil(p/speed) return h if not piles or len(piles) == 0: return 0 start,end = 1,max(piles) while start+1 < end: mid = start + (end-start)//2 h = helper(mid) if h <= H: end = mid else: start = mid return start if helper(start) <= H else end
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
import math class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: if H == len(piles): return max(piles) def possible(K): return sum( math.ceil(p/K) for p in piles) <= H lo, hi = 1, max(piles) while lo <hi: print (lo,hi) mi = (lo+hi)//2 if not possible(mi): lo = mi+1 else: hi = mi return lo
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
import math class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: #1 2 3 4 5 6 7 8 9 10 11 def possible(x): if(x == 0): return False h = 0 for i in piles: h += math.ceil(i/x) return h <= H high = max(piles) low = 1 while(low < high): mid = low + (high-low)//2 if(possible(mid)): high = mid else: low = mid+1 return low
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: K = sum(piles) // H if K == 0: K = 1 while True: hours_needed = 0 for pile in piles: hours_needed += pile // K if pile % K != 0: hours_needed += 1 if hours_needed <= H: return K K += 1
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
# upper_bound: max(piles) # lower_bound: ceil(sum(piles) / H) import math class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: left = math.ceil(sum(piles) / H) right = max(piles) while left <= right: middle = (left + right) // 2 if is_valid(piles, H, middle): right = middle - 1 else: left = middle + 1 return left def is_valid(piles, H, speed): hour = 0 for pile in piles: hour += math.ceil(pile / speed) return hour <= H
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: if H == len(piles): return max(piles) else: if sum(piles)%H == 0: tempMin = sum(piles)//H else: tempMin = sum(piles)//H+1 tempMax = max(piles) while tempMin != tempMax: tempMid = (tempMax-tempMin)//2+tempMin if self.ifOk(piles,H,tempMid): tempMax = tempMid else: tempMin = tempMid + 1 return tempMin def ifOk(self,piles,H,K): hourNeed = 0 for pile in piles: if pile % K == 0: hourNeed = hourNeed + pile // K else: hourNeed = hourNeed + pile // K + 1 if hourNeed > H: return False return True
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def canEatAllBananas(speed): count=0 for pile in piles: if pile>=speed: count+=pile//speed if pile%speed!=0: count+=1 return count<=H low=1 high=max(piles) while low<=high: mid=low+(high-low)//2 if canEatAllBananas(mid): high=mid-1 else: low=mid+1 return low
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def eatingPossible(cap, piles, H): h = 0 for pile in piles: h += pile // cap if pile % cap != 0: h += 1 if h > H: return False return True piles.sort() left = 1 right = max(piles) while left < right: mid = left + (right-left)//2 if eatingPossible(mid, piles, H): right = mid else: left = mid + 1 return left
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
import math class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: total_bananas = sum(piles) left, right = math.ceil(total_bananas / H), max(piles) print(left, right) while left < right: mid = (left + right) // 2 if not sum([math.ceil(pile/mid) for pile in piles]) <= H: left = mid + 1 else: right = mid return left
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def isValid(k): total = 0 for pile in piles: total += math.ceil(pile/k) return total <= H i,j = 1,max(piles) while i < j: mid = i + (j-i)//2 if isValid(mid): j = mid else: i = mid+1 return i
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def time(val): t = len(piles) for pile in piles: t += (pile - 1) // val return t s = sum(piles) l, r = math.ceil(s / H), min(max(piles), math.ceil(s / (H - len(piles) + 1))) while l <= r: mid = l + (r - l) // 2 t = time(mid) if t <= H: r = mid - 1 else: l = mid + 1 return l
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def feasible(threshold): count = 0 for pile in piles: count += math.ceil(pile/threshold) if count > H: return False return True left = 1 right = max(piles) while left < right : mid = left + ((right-left)>>1) if feasible(mid): right = mid else: left = mid+1 return left
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: min_speed = 1 max_speed = max(piles) while min_speed <=max_speed : pivot = min_speed + (max_speed - min_speed)//2 r = sum([math.ceil(x/pivot) for x in piles]) #r=sum(hours) if r == H: return pivot elif min_speed==max_speed and r>=H: return pivot+1 elif r < H: max_speed = pivot-1 elif r > H: min_speed = pivot+1 return pivot
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
import math class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: left = 1 right = max(piles) while(left < right): K = (left+right)//2 hours = 0 for pile in piles: if(pile <= K): hours += 1 else: hours += math.ceil(pile/K) if(hours > H): left = K+1 else: right = K return left
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: low, high = 1, max(piles) def isPossible(eatRate): total = 0 for numBanana in piles: total += ((numBanana-1)//eatRate) + 1 return total <= H while low < high: mid = (low + high) // 2 if isPossible(mid): high = mid else: low = mid + 1 return low
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: n = len(piles) if not n: return -1 def binary_search(l, r): nonlocal piles, H while l < r: mid = (l + r) // 2 if num_hours(mid) <= H: r = mid else: l = mid + 1 return l def num_hours(k): nonlocal n, piles res = 0 for i in range(n): num = piles[i] if k >= num: res += 1 continue res += (num // k) res += 1 if (num % k) else 0 return res return binary_search(1, max(piles))
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: minK = 1 maxK = 0 for pile in piles: if pile > maxK: maxK = pile low = minK high = maxK mid = (low+high)//2 while (low < high): testK = mid if (self.validK(piles, H, mid)): high = mid else: low = mid+1 mid = (low+high)//2 return high def validK(self, piles, H, eatspeed): hourCount = 0 for pile in piles: hoursUsed = ceil(pile/eatspeed) hourCount += hoursUsed if hourCount > H: return False return True
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours.   Example 1: Input: piles = [3,6,7,11], H = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], H = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], H = 6 Output: 23   Constraints: 1 <= piles.length <= 10^4 piles.length <= H <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: lo = 1 hi = max(piles) def ok(K): return sum((1 + (pile - 1) // K) for pile in piles) <= H while lo < hi: mid = (lo + hi) // 2 if ok(mid): hi = mid else: lo = mid + 1 return lo
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], probs: List[float], s: int, t: int) -> float: # first build the graph graph = {u: {} for u in range(n)} for (u, v), prob in zip(edges, probs): graph[u][v] = prob graph[v][u] = prob # run A* search frontier = [(-1, s)] seen = set() while len(frontier) != 0: neg_path_prob, u = heapq.heappop(frontier) if u == t: return -neg_path_prob seen.add(u) for v, edge_prob in graph[u].items(): if v not in seen: heapq.heappush(frontier, (neg_path_prob * edge_prob, v)) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: graph = collections.defaultdict(dict) for edge, prob in zip(edges, succProb): s, t = edge graph[s][t] = prob graph[t][s] = prob heap = [(-1, start)] prob = [0] * n prob[start] = 1 visited = [False] * n while heap: curr_prob, node = heapq.heappop(heap) if visited[node]: continue if node == end: return prob[end] curr_prob *= -1 visited[node] = True for neighbor in graph[node]: if visited[neighbor]: continue p = curr_prob * graph[node][neighbor] if p > prob[neighbor]: prob[neighbor] = p heapq.heappush(heap, (-p, neighbor)) return prob[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: weights = list(map(lambda x:-math.log2(x), succProb)) g = defaultdict(list) for (u, v), w in zip(edges, weights): g[u].append([v, w]) g[v].append([u, w]) dist = {} q = [(0, start)] while q: w, u = heapq.heappop(q) if u in dist: continue dist[u] = w if u == end: break for v, w in g[u]: if v not in dist or dist[v] > dist[u] + w: heapq.heappush(q, (dist[u] + w, v)) return 2 ** (-dist[end]) if end in dist else 0.0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: # bfs only when prob is less than cur best add to the queue graph = [[] for _ in range(n)] for edge, p in zip(edges, succProb): a, b = edge graph[a].append((b, p)) graph[b].append((a, p)) prob = {start: 1} queue = [(start, 1)] while queue: new_queue = [] for a, p_a in queue: for b, p_b in graph[a]: p = p_a*p_b if b not in prob or p > prob[b]: prob[b] = p new_queue.append((b, p)) # print(prob) queue = new_queue return prob.get(end, 0)
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], prob: List[float], start: int, end: int) -> float: weights = list(map(lambda x:-math.log2(x), prob)) g = defaultdict(list) for (u, v), w in zip(edges, weights): g[u].append([v, w]) g[v].append([u, w]) dist = {} q = [(0, start)] while q: w, u = heapq.heappop(q) if u in dist: continue dist[u] = w if u == end: break for v, w in g[u]: if v not in dist or dist[v] > dist[u] + w: heapq.heappush(q, (dist[u] + w, v)) return 2 ** (-dist[end]) if end in dist else 0.0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: graph = defaultdict(list) for (a, b), probability in zip(edges, succProb): graph[a].append([b, probability]) graph[b].append([a, probability]) if start == end: return 1 queue = [[-1, start]] visited = set() distance_map = defaultdict(lambda: float('inf')) while queue: prob, node = heappop(queue) visited.add(node) if node == end: return -prob for neighbour, next_prob in graph[node]: if neighbour in visited: continue heappush(queue, [prob * next_prob, neighbour]) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: dp = [0.0 for _ in range(start)]+[1.0]+[0.0 for _ in range(start+1,n)] dic = defaultdict(list) for e,p in zip(edges, succProb): dic[e[0]].append((e[1],p)) dic[e[1]].append((e[0],p)) queue = deque([start]) while queue: for _ in range(len(queue)): cur = queue.popleft() for c,p in dic[cur]: if dp[cur]*p > dp[c]: dp[c] = dp[cur]*p queue.append(c) return dp[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], prob: List[float], start: int, end: int) -> float: weights = list([-math.log2(x) for x in prob]) g = defaultdict(list) for (u, v), w in zip(edges, weights): g[u].append([v, w]) g[v].append([u, w]) dist = {} q = [(0, start)] while q: w, u = heapq.heappop(q) if u in dist: continue dist[u] = w if u == end: break for v, w in g[u]: if v not in dist or dist[v] > dist[u] + w: heapq.heappush(q, (dist[u] + w, v)) return 2 ** (-dist[end]) if end in dist else 0.0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from heapq import heappop, heappush from sys import maxsize as inf from collections import defaultdict as dic class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: graph = dic(dict) for [u, v], w in zip(edges,succProb): graph[u][v] = w graph[v][u] = w dist = { i : 0 for i in range(n)} dist[start] = 1 visited = set() max_prob = [(-1*1,start)] while len(max_prob): cur_prob, cur_node = heappop(max_prob) if cur_node in visited: continue visited.add(cur_node) for nei in graph[cur_node]: if nei in visited: continue if dist[nei] < graph[cur_node][nei] * (-1*cur_prob): dist[nei] = graph[cur_node][nei] * (-1*cur_prob) heappush(max_prob, ((-1*dist[nei]),nei) ) if cur_node == end: break return(dist[end])
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import defaultdict as ddict from collections import deque class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: maxProb = ddict(float) graph = ddict(dict) for [a,b],sucprob in zip(edges, succProb): graph[a][b] = sucprob if b not in graph[a] else max(sucprob, graph[a][b]) graph[b][a] = sucprob if a not in graph[b] else max(sucprob, graph[b][a]) print(graph) que = deque() que.append((start, 1)) while que: node, prob = que.popleft() maxProb[node] = max(maxProb[node], prob) for child in graph[node]: if prob*graph[node][child] > maxProb[child]: que.append((child, prob*graph[node][child])) return maxProb[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from heapq import heappush, heappop class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: stack = [(-1, start)] paths = [0 for i in range(n)] paths[start] = 1 graph = [{} for i in range(n)] for (source, dstn), weight in zip(edges, succProb): graph[source][dstn] = graph[dstn][source] = weight while stack: _, current = heappop(stack) for v in graph[current]: temp = paths[current] * graph[current][v] if temp > paths[v]: heappush(stack, (-temp, v)) paths[v] = max(temp, paths[v]) return paths[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
import heapq class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: adj = {i:[] for i in range(n)} best = [0] * n for edge, prob in zip(edges, succProb): u, v = edge adj[u].append((v, prob)) adj[v].append((u, prob)) queue = [] heapq.heappush(queue, (-1, start)) while queue: prob, v = heapq.heappop(queue) prob = - prob if v == end: return prob if prob < best[v]: continue best[v] = prob for nxt, np in adj[v]: if nxt != v: tmp = np * prob if tmp > best[nxt]: best[nxt] = tmp heapq.heappush( queue, (-tmp, nxt) ) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
import heapq class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: adj = {i:[] for i in range(n)} best = [0] * n for edge, prob in zip(edges, succProb): u, v = edge adj[u].append((v, prob)) adj[v].append((u, prob)) queue = [] heapq.heappush(queue, (-1, start)) best[start] = 1 while queue: prob, v = heapq.heappop(queue) prob = - prob if v == end: return prob if prob < best[v]: continue for nxt, np in adj[v]: if nxt != v: tmp = np * prob if tmp > best[nxt]: best[nxt] = tmp heapq.heappush( queue, (-tmp, nxt) ) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: dp = [0.0 for _ in range(start)] + [1.0] + [0.0 for _ in range(start+1,n)] # dp[i] is the prob of getting node i from node start graph = defaultdict(list) for (u,v),p in zip(edges,succProb): graph[u].append((v,p)) graph[v].append((u,p)) # dijkstra's algorithm selected = set() heap = [(-1.0, start)] while heap: p, cur = heapq.heappop(heap) selected.add(cur) if cur==end: return -p for child, prob in graph[cur]: if child not in selected and dp[cur]*prob>dp[child]: dp[child] = dp[cur]*prob heapq.heappush(heap, (-dp[child],child)) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
import heapq class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: adj = {i:[] for i in range(n)} best = [0] * n for edge, prob in zip(edges, succProb): u, v = edge adj[u].append((v, prob)) adj[v].append((u, prob)) queue = [] heapq.heappush(queue, (-1, start)) best[start] = 1 while queue: prob, v = heapq.heappop(queue) prob = - prob if v == end: return prob if prob < best[v]: continue best[v] = prob for nxt, np in adj[v]: if nxt != v: tmp = np * prob if tmp > best[nxt]: best[nxt] = tmp heapq.heappush( queue, (-tmp, nxt) ) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import defaultdict, deque class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: stack = deque([start]) paths = [0 for i in range(n)] paths[start] = 1 graph = [{} for i in range(n)] for (source, dstn), weight in zip(edges, succProb): graph[source][dstn] = graph[dstn][source] = weight # seen = set() while stack: current = stack.popleft() for v in graph[current]: temp = paths[current] * graph[current][v] if temp > paths[v]: stack.append(v) paths[v] = max(temp, paths[v]) return paths[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], prob: List[float], start: int, end: int) -> float: weights = list(map(lambda x:-math.log2(x), prob)) g = defaultdict(list) for (u, v), w in zip(edges, weights): g[u].append([v, w]) g[v].append([u, w]) dist = {} q = [(0, start)] while q: w, u = heapq.heappop(q) if u in dist: continue dist[u] = w if u == end: break for v, w in g[u]: if v not in dist or dist[v] > dist[u] + w: heapq.heappush(q, (dist[u] + w, v)) return 2 ** (-dist[end]) if end in dist else 0.0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: def method1(): graph=collections.defaultdict(set) for i,pair in enumerate(edges): u,v=pair graph[u].add((v,succProb[i])) graph[v].add((u,succProb[i])) seen={0:0} queue=[(start,-1)] ans=float('-inf') while queue: node,p=heapq.heappop(queue) p=-p if node==end: ans=max(ans,p) for nei,dw in graph[node]: if (nei not in seen or seen[nei]<p*dw) and p*dw>ans: seen[nei]=p*dw heapq.heappush(queue,(nei,-p*dw)) return ans if ans!=float('-inf') else 0 #return method1() def method2(): AdjList = [set() for _ in range(n)] for (u, v), p in zip(edges, succProb): AdjList[u].add((v, log2(1/p))) AdjList[v].add((u, log2(1/p))) dist = [float('inf') for _ in range(n)] dist[start] = 0 h = [(0, start)] while h: d, u = heappop(h) if d == dist[u]: for (v, p) in AdjList[u]: if dist[u] + p < dist[v]: dist[v] = dist[u] + p heappush(h, (dist[v], v)) return 1 / (2 ** dist[end]) return method2()
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import defaultdict, deque import bisect from sortedcontainers import SortedList # class Solution: # def maxProbability(self, n: int, edges, succProb, start: int, end: int) -> float: # m = [{} for i in range(n)] # for edge, d in zip(edges, succProb): # s, e = edge # m[s][e] = m[e][s] = d # seen = {start: 1} # sorted_e = SortedList([m[start][k], k] for k in m[start]) # while sorted_e: # if end in seen: break # p, e = sorted_e.pop() # seen[e] = p # for tmp_e, tmp_p in m[e].items(): # if tmp_e in seen: continue # new_p = tmp_p * p # sorted_e.add([new_p, tmp_e]) # return seen.get(end, 0) class Solution: def maxProbability(self, n: int, edges, succProb, start: int, end: int) -> float: m = [{} for i in range(n)] for edge, d in zip(edges, succProb): s, e = edge m[s][e] = m[e][s] = d queue = deque([start]) seen = [0] * n seen[start] = 1 while queue: s = queue.popleft() prob = seen[s] for e, p in m[s].items(): tmp = prob * p if seen[e] < tmp: seen[e] = tmp queue.append(e) return seen[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from heapq import heappush, heappop from math import log2 class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: AdjList = [set() for _ in range(n)] for (u, v), p in zip(edges, succProb): AdjList[u].add((v, log2(1/p))) AdjList[v].add((u, log2(1/p))) dist = [float('inf') for _ in range(n)] dist[start] = 0 h = [(0, start)] while h: d, u = heappop(h) if True: for (v, p) in AdjList[u]: if dist[u] + p < dist[v]: dist[v] = dist[u] + p heappush(h, (dist[v], v)) return 1 / (2 ** dist[end])
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n, edges, succProb, start, end) -> float: g = [[] for _ in range(n)] prob = [0. for _ in range(n)] prob[start] = 1. for (a,b), p in zip(edges, succProb): g[a].append((p, b)) g[b].append((p, a)) pq = [(-1., start)] while pq: p, v = heapq.heappop(pq) if prob[v] + p: continue if v == end: return prob[v] for ep, n in g[v]: _p = ep * prob[v] if _p > prob[n]: prob[n] = _p heapq.heappush(pq, (-_p, n)) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import defaultdict, deque class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: stack = deque([start]) paths = {i: 0 for i in range(n)} paths[start] = 1 graph = {i: {} for i in range(n)} for (source, dstn), weight in zip(edges, succProb): graph[source][dstn] = graph[dstn][source] = weight while stack: current = stack.popleft() for v in graph[current]: if paths[current] * graph[current][v] > paths[v]: stack.append(v) paths[v] = max(paths[current] * graph[current][v], paths[v]) return paths[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], probs: List[float], s: int, t: int) -> float: # first build the graph graph = {u: {} for u in range(n)} for (u, v), prob in zip(edges, probs): graph[u][v] = prob graph[v][u] = prob # run DFS/BFS search frontier = [s] path_probs = {u: 0 for u in range(n)} path_probs[s] = 1 while len(frontier) != 0: u = frontier.pop(0) path_prob = path_probs[u] for v, edge_prob in graph[u].items(): if path_prob * edge_prob > path_probs[v]: path_probs[v] = path_prob * edge_prob frontier.append(v) return path_probs[t]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import defaultdict, deque class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: stack = deque([start]) paths = {i: 0 for i in range(n)} paths[start] = 1 graph = defaultdict(dict) for (source, dstn), weight in zip(edges, succProb): graph[source][dstn] = weight graph[dstn][source] = weight while stack: current = stack.popleft() for v in graph[current]: if paths[current] * graph[current][v] > paths[v]: stack.append(v) paths[v] = max(paths[current] * graph[current][v], paths[v]) return paths[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
import heapq class Solution: def maxProbability(self, n: int, edges: List[List[int]], probs: List[float], s: int, t: int) -> float: # first build the graph graph = {u: {} for u in range(n)} for (u, v), prob in zip(edges, probs): graph[u][v] = prob graph[v][u] = prob # run A* search frontier = [(-1, s)] seen = set() while len(frontier) != 0: neg_path_prob, u = heapq.heappop(frontier) if u == t: return -neg_path_prob seen.add(u) for v, edge_prob in graph[u].items(): if v not in seen: heapq.heappush(frontier, (neg_path_prob * edge_prob, v)) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
import heapq from math import log2 class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: AdjList = [set() for _ in range(n)] for (u, v), prob in zip(edges, succProb): AdjList[u].add(( -log2(prob), v )) AdjList[v].add(( -log2(prob), u )) dist = [float('inf')]*n dist[start] = 0 heap = [(0, start)] explored = set() while heap: d, curr = heapq.heappop(heap) explored.add(curr) for (val, node) in AdjList[curr]: if node not in explored: if dist[curr] + val < dist[node]: dist[node] = dist[curr] + val heapq.heappush(heap, (dist[node], node)) return 2 ** (-dist[end])
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import deque class Solution: def maxProbability(self, n: int, edges, succProb, start: int, end: int) -> float: m = [{} for i in range(n)] for edge, d in zip(edges, succProb): s, e = edge m[s][e] = m[e][s] = d res = [0] * n res[start] = 1 q = [[-1, start]] while q and res[end] == 0: tmp = heapq.heappop(q) prob, cur = -tmp[0], tmp[1] res[cur] = prob for nxt, np in m[cur].items(): if res[nxt] != 0: continue heapq.heappush(q, [-np * prob, nxt]) return res[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: graph = collections.defaultdict(list) for (s, e), prob in zip(edges, succProb): graph[s].append((e, prob)) graph[e].append((s, prob)) visited = [0] * n prio = [(-1, start)] while prio: prob, vertex = heapq.heappop(prio) if prob > visited[vertex]: continue visited[vertex] = prob if vertex == end: return -prob for neighbor, cost in graph[vertex]: if prob * cost < visited[neighbor]: visited[neighbor] = prob * cost heapq.heappush(prio, (prob * cost, neighbor)) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: g = defaultdict(list) ''' {0: [(0.5, 1), (0.2, 2)], 1: [(0.5, 0), (0.5, 2)], 2: [(0.5, 1), (0.2, 0)]} ''' for edge, prob in zip(edges, succProb): x, y = edge g[x].append((prob, y)) g[y].append((prob, x)) print(g) q, vis = [(-1, start)], set() cand = [] while q: prob, node = heapq.heappop(q) # print((prob, node)) if node == end: cand.append(-prob) if node not in vis: vis.add(node) for next_prob, nbrs in g[node]: if nbrs not in vis: heapq.heappush(q, (prob * next_prob, nbrs)) print(cand) return max(cand, default=0)
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: # undirected graph # weighted positive edges # single start # shortest path <-> longest path # 最短路 正边权 稀疏图 -》 stack dijkstra N = 100010 dist = [2 for i in range(N)] seen = set() h = [-1 for i in range(N)] e = {} ne = {} w = {} idx = 0 # build singly linked list graph def add(a, b, c, idx): e[idx], w[idx] = b, c ne[idx] = h[a] h[a] = idx for edge, prob in zip(edges, succProb): add(edge[0], edge[1], prob, idx) idx += 1 add(edge[1], edge[0], prob, idx) idx += 1 def heap_dijkstra(): dist[start] = 1 heap = [] heapq.heappush(heap, (-1, start)) while heap: t = heapq.heappop(heap) vertex, distance = t[1], -t[0] if vertex in seen: continue seen.add(vertex) i = h[vertex] # idx while i != -1: j = e[i] if dist[j] == 2 or dist[j] < distance * w[i]: dist[j] = distance * w[i] heapq.heappush(heap, (-dist[j], j)) i = ne[i] return dist[end] ''' graph = [[1e-6 for i in range(N)] for j in range(N)] for edge, prob in zip(edges, succProb): graph[edge[0]][edge[1]] = max(prob, graph[edge[0]][edge[1]]) graph[edge[1]][edge[0]] = max(prob, graph[edge[1]][edge[0]]) def dijkstra(): dist[start] = 1 for i in range(n): t = -1 for j in range(n): if not seen[j] and (t == -1 or dist[t] < dist[j]): t = j seen[t] = True for j in range(n): dist[j] = max(dist[j], dist[t] * graph[t][j]) return dist[end] ''' output = heap_dijkstra() if output == 2 or output < 1e-5: return 0.0 else: return output
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: dp = [0.0 for _ in range(start)] + [1.0] + [0.0 for _ in range(start+1,n)] # dp[i] is the prob of getting node i from node start graph = defaultdict(list) for (u,v),p in zip(edges,succProb): graph[u].append((v,p)) graph[v].append((u,p)) # dijkstra's algorithm heap = [(-1.0, start)] while heap: p, cur = heapq.heappop(heap) if cur==end: return -p for child, prob in graph[cur]: if dp[cur]*prob>dp[child]: dp[child] = dp[cur]*prob heapq.heappush(heap, (-dp[child],child)) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: dist = [-math.inf for _ in range(n)] dist[start] = 1 max_heap = [(1, start)] graph = collections.defaultdict(list) for (u, v), w in zip(edges, succProb): graph[u].append((v, w)) graph[v].append((u, w)) while max_heap: prob, node = heapq.heappop(max_heap) prob = abs(prob) # make it positive to avoid confusion if node == end: return prob for adj, next_prob in graph[node]: # if we are coming from the start node, make sure we don't multiply it by 0 next_prob *= prob if dist[adj] < next_prob: dist[adj] = next_prob heapq.heappush(max_heap, (-next_prob, adj)) return 0.0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import deque from heapq import heappush, heappop class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: graph = [[] for _ in range(n)] for (u, v), wt in zip(edges, succProb): graph[u].append((v, wt)) graph[v].append((u, wt)) probabilities = [0 for _ in range(n)] probabilities[start] = 1 h = [(-probabilities[start], start)] visited = set() while h: curr_prob, curr_node = heappop(h) curr_prob *= -1 visited.add(curr_node) for v, wt in graph[curr_node]: if v not in visited: if probabilities[curr_node] * wt > probabilities[v]: probabilities[v] = probabilities[curr_node] * wt heappush(h, (-probabilities[v], v)) return probabilities[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: dist = [0.0]*n dist[start] = 1.0 for i in range(n): flag = False for (a,b), p in zip(edges, succProb): if dist[a]==0.0 and dist[b]==0.0:continue Max = max(dist[a], dist[b])*p if Max > dist[a]: dist[a] = Max flag = True if Max > dist[b]: dist[b] = Max flag = True if not flag: break return dist[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import defaultdict from heapq import heappush, heappop from typing import List class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: adjlist = defaultdict(list) for edge, succ in zip(edges, succProb): adjlist[edge[0]].append([edge[1], succ]) adjlist[edge[1]].append([edge[0], succ]) cost = [float('-inf')] * n hp = [(-1, start)] visited = set() while hp: price, node = heappop(hp) price = -price if node in visited: continue for neigh, neighcost in adjlist[node]: heappush(hp, (-(price * neighcost), neigh)) cost[node] = price visited.add(node) print(cost) if cost[end] == float('-inf'): return 0 return cost[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from heapq import * from collections import defaultdict class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: # construct graph graph = defaultdict(list) for edge, prob in zip(edges, succProb): src, dst = edge graph[src].append((dst, prob)) graph[dst].append((src, prob)) # Dijkstra (-ve probabilities for max heap) max_heap = [(-1.0, start, None)] while max_heap: probability, node, parent = heappop(max_heap) probability = -probability # print(f\"Node: {node}\") if node == end: return probability neighbors = graph[node] for neighbor, weight in neighbors: # don't go back to the parent if neighbor != parent: heappush(max_heap, (-weight*probability, neighbor, node)) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: g = collections.defaultdict(list) for (u, v), p in zip(edges, succProb): g[u].append((v, p)) g[v].append((u, p)) # print(g) q = [(-1, start)] seen = set() while q: # print(q) p, u = heapq.heappop(q) if u in seen: continue seen.add(u) if u == end: return -p for v, pp in g[u]: # print(v, pp, seen) if v not in seen: heapq.heappush(q, (p * pp, v)) #seen.add(v) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
from collections import defaultdict from heapq import heappop, heappush class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: adjlist = defaultdict(list) for pair, prob in zip(edges, succProb): p, c = pair adjlist[p].append([c, prob]) adjlist[c].append([p, prob]) probability = {i: float('-inf') for i in range(n)} hq = [[-1, start]] visited = set() while hq: cost, curr = heappop(hq) cost = -cost if curr in visited: continue for child, price in adjlist[curr]: heappush(hq, [-(price*cost), child]) visited.add(curr) if probability[curr] < cost: probability[curr] = cost if probability[end] == float('-inf'): return 0 return probability[end]
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: G = defaultdict(list) P = {} for (i, j), p in zip(edges, succProb): G[i].append(j) G[j].append(i) P[i, j] = P[j, i] = p hp = [(-1, start)] seen = {start: 1} while hp: prob, node = heapq.heappop(hp) prob *= -1 if node == end: return prob for nei in G[node]: tmp = seen[node] * P[node, nei] if nei not in seen or seen[nei] < tmp: heapq.heappush(hp, (-tmp, nei)) seen[nei] = tmp return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: dp = [0.0 for _ in range(start)] + [1.0] + [0.0 for _ in range(n)] graph = defaultdict(list) # undirected for (u,v),p in zip(edges,succProb): graph[u].append((v,p)) graph[v].append((u,p)) queue = [(-1.0,start)] # tuple[0] is current point, tuple[1] is prob of getting cur from start while queue: for _ in range(len(queue)): p, cur = heapq.heappop(queue) if cur==end: return -p for child,prob in graph[cur]: if dp[cur]*prob > dp[child]: dp[child] = dp[cur]*prob heapq.heappush(queue,(-dp[child], child)) return 0
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.   Example 1: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. Example 2: Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 Output: 0.30000 Example 3: Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2 Output: 0.00000 Explanation: There is no path between 0 and 2.   Constraints: 2 <= n <= 10^4 0 <= start, end < n start != end 0 <= a, b < n a != b 0 <= succProb.length == edges.length <= 2*10^4 0 <= succProb[i] <= 1 There is at most one edge between every two nodes.
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: dist = [-math.inf for _ in range(n)] dist[start] = 1 max_heap = [(1, start)] # graph = collections.defaultdict(list) graph = collections.defaultdict(dict) for (u, v), w in zip(edges, succProb): # graph[u].append((v, w)) # graph[v].append((u, w)) graph[u][v] = w graph[v][u] = w while max_heap: prob, node = heapq.heappop(max_heap) prob = abs(prob) # make it positive to avoid confusion if node == end: return prob for adj in graph[node]: # if we are coming from the start node, make sure we don't multiply it by 0 next_prob = graph[node][adj] next_prob *= prob if dist[adj] < next_prob: dist[adj] = next_prob heapq.heappush(max_heap, (-next_prob, adj)) return 0.0
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45"
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ dmap={} dmap[0]=s.count('z') dmap[2]=s.count('w') dmap[4]=s.count('u') dmap[6]=s.count('x') dmap[8]=s.count('g') dmap[1]=s.count('o')-dmap[0]-dmap[2]-dmap[4] dmap[3]=s.count('h')-dmap[8] dmap[5]=s.count('f')-dmap[4] dmap[7]=s.count('s')-dmap[6] dmap[9]=s.count('i')-dmap[6]-dmap[8]-dmap[5] res='' #现在的问题就是如何在这里输入 dmap=sorted(list(dmap.items()),key=lambda x:x[0]) lst=['0','1','2','3','4','5','6','7','8','9'] #就是按照第一个来进行排序 ''' lst=['zero','one','two','three','four','five', 'six','seven','eight','nine'] 这个是错误示范 我们需要输出的是数字 字符串 而不是字母 ''' for i in range(len(lst)): res+=lst[i]*dmap[i][1] return res #注意 这道题比较关键的就是需要找到规律才行
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45"
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ order_c = ['w', 'u', 'x', 'g', 'z', 'o', 't', 'f', 'v', 'i'] order_d = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9] cl = [list(e) for e in ['tow', 'four', 'six', 'eight', 'zero', 'one', 'three', 'five', 'seven', 'nine']] digit_cnt = [0] * 10 counter = dict() for c in s: counter[c] = counter.get(c, 0) + 1 for i in range(len(order_c)): cnt = counter.get(order_c[i], 0) digit_cnt[order_d[i]] = cnt if cnt > 0: for c in cl[i]: counter[c] -= cnt ans = list() for i in range(len(digit_cnt)): if digit_cnt[i] > 0: ans.append(('%d' % i) * digit_cnt[i]) return ''.join(ans)
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45"
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ # public solution....beat 96%... res = "" res += "0"*s.count('z') res += "1"*(s.count('o')-s.count('z')-s.count('w')-s.count('u')) res += "2"*s.count('w') res += "3"*(s.count('h') - s.count('g')) res += "4"*s.count('u') res += "5"*(s.count('f') - s.count('u')) res += "6"*s.count('x') res += "7"*(s.count('s')-s.count('x')) res += "8"*s.count("g") res += "9"*(s.count('i') - s.count('x') - s.count("g") - s.count('f') + s.count('u')) return res """ # my solution..........beat 68%.... from collections import Counter dic = Counter(s) res = {0:'', 1:'', 2:'', 3:'', 4:'', 5:'', 6:'', 7:'', 8:'', 9:''} if dic['z'] != 0: res[0] = '0'*dic['z'] s = s.replace('z', '', dic['z']) s = s.replace('e', '', dic['z']) s = s.replace('r', '', dic['z']) s = s.replace('o', '', dic['z']) dic['z'], dic['e'], dic['r'], dic['o'] = 0, dic['e']-dic['z'], dic['r']-dic['z'], dic['o']-dic['z'] if dic['w'] != 0: res[2] = '2'*dic['w'] s = s.replace('t', '', dic['w']) s = s.replace('w', '', dic['w']) s = s.replace('o', '', dic['w']) dic['t'], dic['w'], dic['o'] = dic['t']-dic['w'], 0, dic['o']-dic['w'] if dic['u'] != 0: res[4] = '4'*dic['u'] s = s.replace('f', '', dic['u']) s = s.replace('o', '', dic['u']) s = s.replace('u', '', dic['u']) s = s.replace('r', '', dic['u']) dic['f'], dic['o'], dic['u'], dic['r'] = dic['f']-dic['u'], dic['o']-dic['u'], 0, dic['r']-dic['u'] if dic['x'] != 0: res[6] = '6'*dic['x'] s = s.replace('s', '', dic['x']) s = s.replace('i', '', dic['x']) s = s.replace('x', '', dic['x']) dic['s'], dic['i'], dic['x'] = dic['s']-dic['x'], dic['i']-dic['x'], 0 if dic['g'] != 0: res[8] = '8'*dic['g'] s = s.replace('e', '', dic['g']) s = s.replace('i', '', dic['g']) s = s.replace('g', '', dic['g']) s = s.replace('h', '', dic['g']) s = s.replace('t', '', dic['g']) dic['e'], dic['i'], dic['g'], dic['h'], dic['t'] = dic['e']-dic['g'], dic['i']-dic['g'], 0, dic['h']-dic['g'], dic['t']-dic['g'] if dic['s'] != 0: res[7] = '7'*dic['s'] s = s.replace('s', '', dic['s']) s = s.replace('e', '', 2*dic['s']) s = s.replace('v', '', dic['s']) s = s.replace('n', '', dic['s']) dic['s'], dic['e'], dic['v'], dic['n'] = 0, dic['e']-2*dic['s'], dic['v']-dic['s'], dic['n']-dic['s'] if dic['r'] != 0: res[3] = '3'*dic['r'] s = s.replace('t', '', dic['r']) s = s.replace('h', '', dic['r']) s = s.replace('r', '', dic['r']) s = s.replace('e', '', 2*dic['r']) dic['t'], dic['h'], dic['r'], dic['e'] = dic['t']-dic['r'], dic['h']-dic['r'], 0, dic['e']-2*dic['r'] if dic['v'] != 0: res[5] = '5'*dic['v'] s = s.replace('f', '', dic['v']) s = s.replace('i', '', dic['v']) s = s.replace('v', '', dic['v']) s = s.replace('e', '', dic['v']) dic['f'], dic['i'], dic['v'], dic['e'] = dic['f']-dic['v'], dic['i']-dic['v'], 0, dic['e']-dic['v'] if dic['i'] != 0: res[9] = '9'*dic['i'] s = s.replace('n', '', 2*dic['i']) s = s.replace('i', '', dic['i']) s = s.replace('e', '', dic['i']) dic['n'], dic['i'], dic['e'] = dic['n']-2*dic['i'], 0, dic['e']-dic['i'] if dic['n'] != 0: res[1] = '1'*dic['n'] s = s.replace('o', '', dic['n']) s = s.replace('n', '', dic['n']) s = s.replace('e', '', dic['n']) dic['o'], dic['n'], dic['e'] = dic['o']-dic['n'], 0, dic['e']-dic['n'] return res[0]+res[1]+res[2]+res[3]+res[4]+res[5]+res[6]+res[7]+res[8]+res[9] """
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45"
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ res = "" res += "0"*s.count('z') res += "1"*(s.count('o')-s.count('z')-s.count('w')-s.count('u')) res += "2"*s.count('w') res += "3"*(s.count('h') - s.count('g')) res += "4"*s.count('u') res += "5"*(s.count('f') - s.count('u')) res += "6"*s.count('x') res += "7"*(s.count('s')-s.count('x')) res += "8"*s.count("g") res += "9"*(s.count('i') - s.count('x') - s.count("g") - s.count('f') + s.count('u')) return res """ # my solution..........beat 68%.... from collections import Counter dic = Counter(s) res = {0:'', 1:'', 2:'', 3:'', 4:'', 5:'', 6:'', 7:'', 8:'', 9:''} if dic['z'] != 0: res[0] = '0'*dic['z'] s = s.replace('z', '', dic['z']) s = s.replace('e', '', dic['z']) s = s.replace('r', '', dic['z']) s = s.replace('o', '', dic['z']) dic['z'], dic['e'], dic['r'], dic['o'] = 0, dic['e']-dic['z'], dic['r']-dic['z'], dic['o']-dic['z'] if dic['w'] != 0: res[2] = '2'*dic['w'] s = s.replace('t', '', dic['w']) s = s.replace('w', '', dic['w']) s = s.replace('o', '', dic['w']) dic['t'], dic['w'], dic['o'] = dic['t']-dic['w'], 0, dic['o']-dic['w'] if dic['u'] != 0: res[4] = '4'*dic['u'] s = s.replace('f', '', dic['u']) s = s.replace('o', '', dic['u']) s = s.replace('u', '', dic['u']) s = s.replace('r', '', dic['u']) dic['f'], dic['o'], dic['u'], dic['r'] = dic['f']-dic['u'], dic['o']-dic['u'], 0, dic['r']-dic['u'] if dic['x'] != 0: res[6] = '6'*dic['x'] s = s.replace('s', '', dic['x']) s = s.replace('i', '', dic['x']) s = s.replace('x', '', dic['x']) dic['s'], dic['i'], dic['x'] = dic['s']-dic['x'], dic['i']-dic['x'], 0 if dic['g'] != 0: res[8] = '8'*dic['g'] s = s.replace('e', '', dic['g']) s = s.replace('i', '', dic['g']) s = s.replace('g', '', dic['g']) s = s.replace('h', '', dic['g']) s = s.replace('t', '', dic['g']) dic['e'], dic['i'], dic['g'], dic['h'], dic['t'] = dic['e']-dic['g'], dic['i']-dic['g'], 0, dic['h']-dic['g'], dic['t']-dic['g'] if dic['s'] != 0: res[7] = '7'*dic['s'] s = s.replace('s', '', dic['s']) s = s.replace('e', '', 2*dic['s']) s = s.replace('v', '', dic['s']) s = s.replace('n', '', dic['s']) dic['s'], dic['e'], dic['v'], dic['n'] = 0, dic['e']-2*dic['s'], dic['v']-dic['s'], dic['n']-dic['s'] if dic['r'] != 0: res[3] = '3'*dic['r'] s = s.replace('t', '', dic['r']) s = s.replace('h', '', dic['r']) s = s.replace('r', '', dic['r']) s = s.replace('e', '', 2*dic['r']) dic['t'], dic['h'], dic['r'], dic['e'] = dic['t']-dic['r'], dic['h']-dic['r'], 0, dic['e']-2*dic['r'] if dic['v'] != 0: res[5] = '5'*dic['v'] s = s.replace('f', '', dic['v']) s = s.replace('i', '', dic['v']) s = s.replace('v', '', dic['v']) s = s.replace('e', '', dic['v']) dic['f'], dic['i'], dic['v'], dic['e'] = dic['f']-dic['v'], dic['i']-dic['v'], 0, dic['e']-dic['v'] if dic['i'] != 0: res[9] = '9'*dic['i'] s = s.replace('n', '', 2*dic['i']) s = s.replace('i', '', dic['i']) s = s.replace('e', '', dic['i']) dic['n'], dic['i'], dic['e'] = dic['n']-2*dic['i'], 0, dic['e']-dic['i'] if dic['n'] != 0: res[1] = '1'*dic['n'] s = s.replace('o', '', dic['n']) s = s.replace('n', '', dic['n']) s = s.replace('e', '', dic['n']) dic['o'], dic['n'], dic['e'] = dic['o']-dic['n'], 0, dic['e']-dic['n'] return res[0]+res[1]+res[2]+res[3]+res[4]+res[5]+res[6]+res[7]+res[8]+res[9] """
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45"
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ # public solution....beat 96%... res = "" res += "0"*s.count('z') res += "1"*(s.count('o')-s.count('z')-s.count('w')-s.count('u')) res += "2"*s.count('w') res += "3"*(s.count('h') - s.count('g')) res += "4"*s.count('u') res += "5"*(s.count('f') - s.count('u')) res += "6"*s.count('x') res += "7"*(s.count('s')-s.count('x')) res += "8"*s.count("g") res += "9"*(s.count('i') - s.count('x') - s.count("g") - s.count('f') + s.count('u')) return res """ # my solution..........beat 68%.... from collections import Counter dic = Counter(s) res = {0:'', 1:'', 2:'', 3:'', 4:'', 5:'', 6:'', 7:'', 8:'', 9:''} if dic['z'] != 0: res[0] = '0'*dic['z'] s = s.replace('z', '', dic['z']) s = s.replace('e', '', dic['z']) s = s.replace('r', '', dic['z']) s = s.replace('o', '', dic['z']) dic['z'], dic['e'], dic['r'], dic['o'] = 0, dic['e']-dic['z'], dic['r']-dic['z'], dic['o']-dic['z'] if dic['w'] != 0: res[2] = '2'*dic['w'] s = s.replace('t', '', dic['w']) s = s.replace('w', '', dic['w']) s = s.replace('o', '', dic['w']) dic['t'], dic['w'], dic['o'] = dic['t']-dic['w'], 0, dic['o']-dic['w'] if dic['u'] != 0: res[4] = '4'*dic['u'] s = s.replace('f', '', dic['u']) s = s.replace('o', '', dic['u']) s = s.replace('u', '', dic['u']) s = s.replace('r', '', dic['u']) dic['f'], dic['o'], dic['u'], dic['r'] = dic['f']-dic['u'], dic['o']-dic['u'], 0, dic['r']-dic['u'] if dic['x'] != 0: res[6] = '6'*dic['x'] s = s.replace('s', '', dic['x']) s = s.replace('i', '', dic['x']) s = s.replace('x', '', dic['x']) dic['s'], dic['i'], dic['x'] = dic['s']-dic['x'], dic['i']-dic['x'], 0 if dic['g'] != 0: res[8] = '8'*dic['g'] s = s.replace('e', '', dic['g']) s = s.replace('i', '', dic['g']) s = s.replace('g', '', dic['g']) s = s.replace('h', '', dic['g']) s = s.replace('t', '', dic['g']) dic['e'], dic['i'], dic['g'], dic['h'], dic['t'] = dic['e']-dic['g'], dic['i']-dic['g'], 0, dic['h']-dic['g'], dic['t']-dic['g'] if dic['s'] != 0: res[7] = '7'*dic['s'] s = s.replace('s', '', dic['s']) s = s.replace('e', '', 2*dic['s']) s = s.replace('v', '', dic['s']) s = s.replace('n', '', dic['s']) dic['s'], dic['e'], dic['v'], dic['n'] = 0, dic['e']-2*dic['s'], dic['v']-dic['s'], dic['n']-dic['s'] if dic['r'] != 0: res[3] = '3'*dic['r'] s = s.replace('t', '', dic['r']) s = s.replace('h', '', dic['r']) s = s.replace('r', '', dic['r']) s = s.replace('e', '', 2*dic['r']) dic['t'], dic['h'], dic['r'], dic['e'] = dic['t']-dic['r'], dic['h']-dic['r'], 0, dic['e']-2*dic['r'] if dic['v'] != 0: res[5] = '5'*dic['v'] s = s.replace('f', '', dic['v']) s = s.replace('i', '', dic['v']) s = s.replace('v', '', dic['v']) s = s.replace('e', '', dic['v']) dic['f'], dic['i'], dic['v'], dic['e'] = dic['f']-dic['v'], dic['i']-dic['v'], 0, dic['e']-dic['v'] if dic['i'] != 0: res[9] = '9'*dic['i'] s = s.replace('n', '', 2*dic['i']) s = s.replace('i', '', dic['i']) s = s.replace('e', '', dic['i']) dic['n'], dic['i'], dic['e'] = dic['n']-2*dic['i'], 0, dic['e']-dic['i'] if dic['n'] != 0: res[1] = '1'*dic['n'] s = s.replace('o', '', dic['n']) s = s.replace('n', '', dic['n']) s = s.replace('e', '', dic['n']) dic['o'], dic['n'], dic['e'] = dic['o']-dic['n'], 0, dic['e']-dic['n'] return res[0]+res[1]+res[2]+res[3]+res[4]+res[5]+res[6]+res[7]+res[8]+res[9] """
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45"
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ ''' # unique letter in nums: zero, two, four, six, eight uniques = [['z', 'w', 'u', 'x', 'g'], ['zero', 'two', 'four', 'six', 'eight'], ['0', '2', '4', '6', '8']] # then the leftover are: one, three, five, seven, nine # the unique letter in each is: except nine leftover = [['o', 't', 'f', 's'], ['one', 'three', 'five', 'seven'], ['1', '3', '5', '7']] res = '' count = collections.Counter(s) for l in uniques[0]: cntl = count[l] if cntl != 0: idx = uniques[0].index(l) res += uniques[2][idx]*cntl for m in uniques[1][idx]: s = s.replace(m, '', cntl) count[m] -= cntl #return s for l in leftover[0]: cntl = count[l] if cntl != 0: idx = leftover[0].index(l) res += leftover[2][idx]*cntl for m in leftover[1][idx]: s = s.replace(m, '', cntl) count[m] -= cntl res += '9'*count['i'] return ''.join(letter for letter in sorted(res)) ''' dump = dict() dump[0] = s.count('z') dump[2] = s.count('w') dump[4] = s.count('u') dump[6] = s.count('x') dump[8] = s.count('g') dump[5] = s.count('f') - dump[4] dump[7] = s.count('s') - dump[6] dump[3] = s.count('h') - dump[8] dump[1] = s.count('o') - dump[0] - dump[2] - dump[4] dump[9] = s.count('i') - dump[5] - dump[6] - dump[8] tmp = '' for i in range(10): tmp += str(i)*dump[i] return ''.join(letter for letter in sorted(tmp))
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45"
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ d=collections.defaultdict(int) for i in s: d[i]+=1 zero='0'*d['z'] d['e']-=d['z'] d['r']-=d['z'] d['o']-=d['z'] two='2'*d['w'] d['t']-=d['w'] d['o']-=d['w'] four='4'*d['u'] d['f']-=d['u'] d['o']-=d['u'] d['r']-=d['u'] five='5'*d['f'] d['i']-=d['f'] d['v']-=d['f'] d['e']-=d['f'] six='6'*d['x'] d['s']-=d['x'] d['i']-=d['x'] seven='7'*d['v'] d['s']-=d['v'] d['e']-=d['v']*2 d['n']-=d['v'] eight='8'*d['g'] d['e']-=d['g'] d['i']-=d['g'] d['h']-=d['g'] d['t']-=d['g'] nine='9'*d['i'] d['n']-=d['i']*2 d['e']-=d['i'] one='1'*d['o'] three='3'*d['r'] return zero+one+two+three+four+five+six+seven+eight+nine
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45"
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ from collections import Counter dic = Counter(s) res = {0:'', 1:'', 2:'', 3:'', 4:'', 5:'', 6:'', 7:'', 8:'', 9:''} if dic['z'] != 0: res[0] = '0'*dic['z'] s = s.replace('z', '', dic['z']) s = s.replace('e', '', dic['z']) s = s.replace('r', '', dic['z']) s = s.replace('o', '', dic['z']) dic['z'], dic['e'], dic['r'], dic['o'] = 0, dic['e']-dic['z'], dic['r']-dic['z'], dic['o']-dic['z'] if dic['w'] != 0: res[2] = '2'*dic['w'] s = s.replace('t', '', dic['w']) s = s.replace('w', '', dic['w']) s = s.replace('o', '', dic['w']) dic['t'], dic['w'], dic['o'] = dic['t']-dic['w'], 0, dic['o']-dic['w'] if dic['u'] != 0: res[4] = '4'*dic['u'] s = s.replace('f', '', dic['u']) s = s.replace('o', '', dic['u']) s = s.replace('u', '', dic['u']) s = s.replace('r', '', dic['u']) dic['f'], dic['o'], dic['u'], dic['r'] = dic['f']-dic['u'], dic['o']-dic['u'], 0, dic['r']-dic['u'] if dic['x'] != 0: res[6] = '6'*dic['x'] s = s.replace('s', '', dic['x']) s = s.replace('i', '', dic['x']) s = s.replace('x', '', dic['x']) dic['s'], dic['i'], dic['x'] = dic['s']-dic['x'], dic['i']-dic['x'], 0 if dic['g'] != 0: res[8] = '8'*dic['g'] s = s.replace('e', '', dic['g']) s = s.replace('i', '', dic['g']) s = s.replace('g', '', dic['g']) s = s.replace('h', '', dic['g']) s = s.replace('t', '', dic['g']) dic['e'], dic['i'], dic['g'], dic['h'], dic['t'] = dic['e']-dic['g'], dic['i']-dic['g'], 0, dic['h']-dic['g'], dic['t']-dic['g'] if dic['s'] != 0: res[7] = '7'*dic['s'] s = s.replace('s', '', dic['s']) s = s.replace('e', '', 2*dic['s']) s = s.replace('v', '', dic['s']) s = s.replace('n', '', dic['s']) dic['s'], dic['e'], dic['v'], dic['n'] = 0, dic['e']-2*dic['s'], dic['v']-dic['s'], dic['n']-dic['s'] if dic['r'] != 0: res[3] = '3'*dic['r'] s = s.replace('t', '', dic['r']) s = s.replace('h', '', dic['r']) s = s.replace('r', '', dic['r']) s = s.replace('e', '', 2*dic['r']) dic['t'], dic['h'], dic['r'], dic['e'] = dic['t']-dic['r'], dic['h']-dic['r'], 0, dic['e']-2*dic['r'] if dic['v'] != 0: res[5] = '5'*dic['v'] s = s.replace('f', '', dic['v']) s = s.replace('i', '', dic['v']) s = s.replace('v', '', dic['v']) s = s.replace('e', '', dic['v']) dic['f'], dic['i'], dic['v'], dic['e'] = dic['f']-dic['v'], dic['i']-dic['v'], 0, dic['e']-dic['v'] if dic['i'] != 0: res[9] = '9'*dic['i'] s = s.replace('n', '', 2*dic['i']) s = s.replace('i', '', dic['i']) s = s.replace('e', '', dic['i']) dic['n'], dic['i'], dic['e'] = dic['n']-2*dic['i'], 0, dic['e']-dic['i'] if dic['n'] != 0: res[1] = '1'*dic['n'] s = s.replace('o', '', dic['n']) s = s.replace('n', '', dic['n']) s = s.replace('e', '', dic['n']) dic['o'], dic['n'], dic['e'] = dic['o']-dic['n'], 0, dic['e']-dic['n'] return res[0]+res[1]+res[2]+res[3]+res[4]+res[5]+res[6]+res[7]+res[8]+res[9]
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45"
class Solution: def originalDigits(self, s): """ :type s: str :rtype: str """ from collections import Counter dic = Counter(s) res = {0:'', 1:'', 2:'', 3:'', 4:'', 5:'', 6:'', 7:'', 8:'', 9:''} if dic['z'] != 0: res[0] = '0'*dic['z'] s = s.replace('z', '', dic['z']) s = s.replace('e', '', dic['z']) s = s.replace('r', '', dic['z']) s = s.replace('o', '', dic['z']) dic['z'], dic['e'], dic['r'], dic['o'] = 0, dic['e']-dic['z'], dic['r']-dic['z'], dic['o']-dic['z'] if dic['w'] != 0: res[2] = '2'*dic['w'] s = s.replace('t', '', dic['w']) s = s.replace('w', '', dic['w']) s = s.replace('o', '', dic['w']) dic['t'], dic['w'], dic['o'] = dic['t']-dic['w'], 0, dic['o']-dic['w'] if dic['u'] != 0: res[4] = '4'*dic['u'] s = s.replace('f', '', dic['u']) s = s.replace('o', '', dic['u']) s = s.replace('u', '', dic['u']) s = s.replace('r', '', dic['u']) dic['f'], dic['o'], dic['u'], dic['r'] = dic['f']-dic['u'], dic['o']-dic['u'], 0, dic['r']-dic['u'] if dic['x'] != 0: res[6] = '6'*dic['x'] s = s.replace('s', '', dic['x']) s = s.replace('i', '', dic['x']) s = s.replace('x', '', dic['x']) dic['s'], dic['i'], dic['x'] = dic['s']-dic['x'], dic['i']-dic['x'], 0 if dic['g'] != 0: res[8] = '8'*dic['g'] s = s.replace('e', '', dic['g']) s = s.replace('i', '', dic['g']) s = s.replace('g', '', dic['g']) s = s.replace('h', '', dic['g']) s = s.replace('t', '', dic['g']) dic['e'], dic['i'], dic['g'], dic['h'], dic['t'] = dic['e']-dic['g'], dic['i']-dic['g'], 0, dic['h']-dic['g'], dic['t']-dic['g'] if dic['s'] != 0: res[7] = '7'*dic['s'] s = s.replace('s', '', dic['s']) s = s.replace('e', '', 2*dic['s']) s = s.replace('v', '', dic['s']) s = s.replace('n', '', dic['s']) dic['s'], dic['e'], dic['v'], dic['n'] = 0, dic['e']-2*dic['s'], dic['v']-dic['s'], dic['n']-dic['s'] if dic['r'] != 0: res[3] = '3'*dic['r'] s = s.replace('t', '', dic['r']) s = s.replace('h', '', dic['r']) s = s.replace('r', '', dic['r']) s = s.replace('e', '', 2*dic['r']) dic['t'], dic['h'], dic['r'], dic['e'] = dic['t']-dic['r'], dic['h']-dic['r'], 0, dic['e']-2*dic['r'] if dic['v'] != 0: res[5] = '5'*dic['v'] s = s.replace('f', '', dic['v']) s = s.replace('i', '', dic['v']) s = s.replace('v', '', dic['v']) s = s.replace('e', '', dic['v']) dic['f'], dic['i'], dic['v'], dic['e'] = dic['f']-dic['v'], dic['i']-dic['v'], 0, dic['e']-dic['v'] if dic['i'] != 0: res[9] = '9'*dic['i'] s = s.replace('n', '', 2*dic['i']) s = s.replace('i', '', dic['i']) s = s.replace('e', '', dic['i']) dic['n'], dic['i'], dic['e'] = dic['n']-2*dic['i'], 0, dic['e']-dic['i'] if dic['n'] != 0: res[1] = '1'*dic['n'] s = s.replace('o', '', dic['n']) s = s.replace('n', '', dic['n']) s = s.replace('e', '', dic['n']) dic['o'], dic['n'], dic['e'] = dic['o']-dic['n'], 0, dic['e']-dic['n'] return res[0]+res[1]+res[2]+res[3]+res[4]+res[5]+res[6]+res[7]+res[8]+res[9]
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example 3: Input: nums = [19], threshold = 5 Output: 4   Constraints: 1 <= nums.length <= 5 * 10^4 1 <= nums[i] <= 10^6 nums.length <= threshold <= 10^6
import numpy as np import math class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: if len(nums) == 1: return int(math.ceil(nums[0]/threshold)) np_nums = np.array(nums) low, high = 1, np.max(np_nums) divisors = [] while low + 1 < high: mid = (low + high) // 2 if np.sum(np.ceil(np_nums/mid)) > threshold: low = mid else: high = mid if np.sum(np.ceil(np_nums/low)) <= threshold: return low return high
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example 3: Input: nums = [19], threshold = 5 Output: 4   Constraints: 1 <= nums.length <= 5 * 10^4 1 <= nums[i] <= 10^6 nums.length <= threshold <= 10^6
from numpy import array, ceil, sum class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: nums = array(nums) l, r = ceil(sum(nums)/threshold), max(nums) while l < r: mid = (l+r)//2 if sum(ceil(nums/mid)) <= threshold: r = mid else: l = mid + 1 return int(r)
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example 3: Input: nums = [19], threshold = 5 Output: 4   Constraints: 1 <= nums.length <= 5 * 10^4 1 <= nums[i] <= 10^6 nums.length <= threshold <= 10^6
class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: def helper(nums, ans): return sum([ (i + ans - 1) // ans for i in nums]) l = 1 r = max(nums) while l < r: mid = l + (r - l) // 2 sumv = helper(nums, mid) if sumv <= threshold: r = mid else: l = mid + 1 return l
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example 3: Input: nums = [19], threshold = 5 Output: 4   Constraints: 1 <= nums.length <= 5 * 10^4 1 <= nums[i] <= 10^6 nums.length <= threshold <= 10^6
import math class Solution: def calculateSum(self, nums, divisor): Sum = 0 for num in nums: Sum += math.ceil(num / divisor) return Sum def smallestDivisor(self, nums: List[int], threshold: int) -> int: maxValue = max(nums) l = 1 r = maxValue while l <= r: mid = (l + r) // 2 # print(mid) if mid == maxValue: return maxValue sum1 = self.calculateSum(nums, mid) sum2 = self.calculateSum(nums, mid + 1) # print(sum1, sum2) if sum2 <= threshold and sum1 > threshold: return mid + 1 if sum1 <= threshold: r = mid - 1 if sum1 > threshold: l = mid + 1 return 1
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example 3: Input: nums = [19], threshold = 5 Output: 4   Constraints: 1 <= nums.length <= 5 * 10^4 1 <= nums[i] <= 10^6 nums.length <= threshold <= 10^6
class Solution: def divide(self, num, divisor): return -((-num)//divisor) def getQuotient(self, nums, divisor): output = 0 for num in nums: output += ceil(num/divisor) return output def getResult(self, results, divisor, nums): #if divisor in results: # return results[divisor] #else: # results[divisor] = self.getQuotient(nums, divisor) # return results[divisor] return self.getQuotient(nums, divisor) def helper(self, results, nums, i, j, threshold): if i == j: return i mid = (i+j)//2 if mid == 1: return mid elif self.getResult(results, mid, nums) <= threshold and self.getResult(results, mid-1, nums) > threshold: return mid elif self.getResult(results, mid, nums) <= threshold: return self.helper(results, nums, i, mid-1, threshold) else: return self.helper(results, nums, mid+1, j, threshold) def smallestDivisor(self, nums: List[int], threshold: int) -> int: maxDivisor = ceil(2*sum(nums)/threshold) #print(maxDivisor) #maxDivisor = 1000000 results = dict() return self.helper(results, nums, 1, maxDivisor, threshold)
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example 3: Input: nums = [19], threshold = 5 Output: 4   Constraints: 1 <= nums.length <= 5 * 10^4 1 <= nums[i] <= 10^6 nums.length <= threshold <= 10^6
class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: lo, hi= 1, max(nums) while lo <= hi: mid = (lo + hi) // 2 if sum([math.ceil(i/mid) for i in nums]) <= threshold: hi = mid - 1 else: lo = mid + 1 return lo
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example 3: Input: nums = [19], threshold = 5 Output: 4   Constraints: 1 <= nums.length <= 5 * 10^4 1 <= nums[i] <= 10^6 nums.length <= threshold <= 10^6
import math class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: # left, right = 1, max(nums) # while left + 1 < right: # mid = (left + right) // 2 # div_sum = self.get_sum(mid, nums) # if div_sum > threshold: # left = mid # else: # right = mid # div_sum = self.get_sum(left, nums) # if div_sum <= threshold: # return left # return right # def get_sum(self, divisor, nums): # res = 0 # for n in nums: # tmp = n // divisor # if tmp * divisor < n: # tmp += 1 # res += tmp # return res dicti = {0:False} def chk(nmb): if nmb in dicti: return dicti[nmb] val = 0 for num in nums: val += math.ceil(num/nmb) if val > threshold: dicti[nmb] = False return False dicti[nmb] = True return dicti[nmb] high = sum(nums) low = math.ceil(high/threshold) while low <= high: mid = (low + high)//2 if chk(mid): high = mid - 1 elif not chk(mid): low = mid + 1 return low-1 if chk(low-1) else high+1
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example 3: Input: nums = [19], threshold = 5 Output: 4   Constraints: 1 <= nums.length <= 5 * 10^4 1 <= nums[i] <= 10^6 nums.length <= threshold <= 10^6
class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: l, r = 1, max(nums) while l < r: m = (l + r) // 2 sum_num = 0 for i in nums: sum_num += (i + m - 1) // m if sum_num > threshold: l = m + 1 else: r = m return l
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer.   Example 1: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example 2: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example 3: Input: nums = [19], threshold = 5 Output: 4   Constraints: 1 <= nums.length <= 5 * 10^4 1 <= nums[i] <= 10^6 nums.length <= threshold <= 10^6
class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: # if the sum <= threshold, the divisor is big enough low, high = 1, max(nums) while low < high: mid = (low + high) // 2 # if the sum > threshold, the divisor is too small if sum((i + mid - 1) // mid for i in nums) > threshold: low = mid + 1 else: high = mid return low