post_href stringlengths 57 213 | python_solutions stringlengths 71 22.3k | slug stringlengths 3 77 | post_title stringlengths 1 100 | user stringlengths 3 29 | upvotes int64 -20 1.2k | views int64 0 60.9k | problem_title stringlengths 3 77 | number int64 1 2.48k | acceptance float64 0.14 0.91 | difficulty stringclasses 3 values | __index_level_0__ int64 0 34k |
|---|---|---|---|---|---|---|---|---|---|---|---|
https://leetcode.com/problems/daily-temperatures/discuss/1842807/Python-solution-using-namedtuple | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
temp_tuple = collections.namedtuple('Temp', ('temp', 'day'))
ans = [0 for _ in range(len(temperatures))]
stack = [temp_tuple(temperatures[0], 0)]
for i, t in enumerate(temperatures):
if i == 0:
continue
if t < stack[-1].temp:
stack.append(temp_tuple(t, i))
else:
while stack and stack[-1].temp < t:
last = stack.pop()
ans[last.day] = i - last.day
# print(last.day, last.temp)
stack.append(temp_tuple(t, i))
return ans | daily-temperatures | Python solution using namedtuple | mitani-reishi116 | 0 | 43 | daily temperatures | 739 | 0.666 | Medium | 12,100 |
https://leetcode.com/problems/daily-temperatures/discuss/1635721/Easy-Python-Solution-using-Stack-O(N) | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
store = {}
stack = []
result = [0]*n
stack.append(0)
for i in range(1,n):
if temperatures[i]>temperatures[stack[-1]]:
while len(stack)>0 and temperatures[i]>temperatures[stack[-1]]:
popped = stack.pop()
result[popped] = i - popped
stack.append(i)
else:
stack.append(i)
return result | daily-temperatures | Easy Python Solution using Stack O(N) | RG97 | 0 | 88 | daily temperatures | 739 | 0.666 | Medium | 12,101 |
https://leetcode.com/problems/daily-temperatures/discuss/1620977/Stack-Easy-Understanding-Python-Beats-63.65-of-python3-submissions | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
n = len(temperatures)
output = [None] * n
for i in range(n-1,-1,-1):
while stack and temperatures[stack[-1]] <= temperatures[i]:
stack.pop()
output[i] = stack[-1] - i if stack else 0
stack.append(i)
return output | daily-temperatures | Stack, Easy Understanding, Python, Beats 63.65 % of python3 submissions | jasonguan0107 | 0 | 123 | daily temperatures | 739 | 0.666 | Medium | 12,102 |
https://leetcode.com/problems/daily-temperatures/discuss/1594896/Monotonic-Stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = [] #monotonous stack
n = len(temperatures)
ans = [0]*n
for i in range(n-1, -1, -1):
while stack!=[] and temperatures[i]>=stack[-1][0]:
stack.pop(-1)
if stack==[]: ans[i] = 0
else: ans[i] = stack[-1][1]-i
stack.append((temperatures[i], i)) #each entry is a value-index pair
return ans | daily-temperatures | Monotonic Stack | steven0821 | 0 | 171 | daily temperatures | 739 | 0.666 | Medium | 12,103 |
https://leetcode.com/problems/daily-temperatures/discuss/1576122/Python-stack-solution-faster-than-79 | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
res = [0] * len(temperatures)
for i, temp in enumerate(temperatures):
while stack and temp > stack[-1][0]:
res[stack[-1][1]] = i - stack[-1][1]
stack.pop()
stack.append((temp, i))
return res | daily-temperatures | Python stack solution faster than 79% | dereky4 | 0 | 99 | daily temperatures | 739 | 0.666 | Medium | 12,104 |
https://leetcode.com/problems/daily-temperatures/discuss/1574768/ez-python-stack-solution | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
output_rev = []
day = len(temperatures) - 1
for temp in temperatures[::-1]:
if not stack:
output_rev.append(0)
stack.append([temp,day])
else:
while stack and temp >= stack[-1][0]:
stack.pop()
if stack:
output_rev.append(stack[-1][1] - day)
else:
output_rev.append(0)
stack.append([temp,day])
day -= 1
return output_rev[::-1] | daily-temperatures | ez python stack solution | yingziqing123 | 0 | 62 | daily temperatures | 739 | 0.666 | Medium | 12,105 |
https://leetcode.com/problems/daily-temperatures/discuss/1517688/Python-Simple-Stack-Solution-with-Explanation | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n, stack = len(temperatures), []
res = [0] * n
for i in reversed(range(n)):
while stack and temperatures[stack[-1]] <= temperatures[i]:
stack.pop()
if stack:
res[i] = stack[-1] - i
stack.append(i)
return res | daily-temperatures | [Python] Simple Stack Solution with Explanation | Saksham003 | 0 | 162 | daily temperatures | 739 | 0.666 | Medium | 12,106 |
https://leetcode.com/problems/daily-temperatures/discuss/1462642/Simply-monotonic-stack-in-Python | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n, ms = len(temperatures), [0]
r = [0] * n
for i in range(1, n):
while ms and temperatures[ms[-1]] < temperatures[i]:
r[ms.pop()] = i - ms[-1]
ms += i,
return r | daily-temperatures | Simply monotonic stack in Python | mousun224 | 0 | 134 | daily temperatures | 739 | 0.666 | Medium | 12,107 |
https://leetcode.com/problems/daily-temperatures/discuss/1447283/Simple-Python-O(n)-monotonic-stack-solution | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
ret = [0]*len(temperatures)
mono_stack = []
for i, t in enumerate(temperatures):
while mono_stack and mono_stack[-1][0] < t:
_, prev_i = mono_stack.pop()
ret[prev_i] = i-prev_i
mono_stack.append((t, i))
return ret | daily-temperatures | Simple Python O(n) monotonic stack solution | Charlesl0129 | 0 | 146 | daily temperatures | 739 | 0.666 | Medium | 12,108 |
https://leetcode.com/problems/daily-temperatures/discuss/1314388/Python3-solution-using-stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
ans = [0]*len(temperatures)
st = []
for i,j in enumerate(temperatures):
while st and j > st[-1][0]:
x,y = st.pop()
ans[y] = i - y
st.append((j,i))
return ans | daily-temperatures | Python3 solution using stack | EklavyaJoshi | 0 | 157 | daily temperatures | 739 | 0.666 | Medium | 12,109 |
https://leetcode.com/problems/daily-temperatures/discuss/761486/Python-or-Need-Suggestions-to-improve-complexity | class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
start = first = 0
res = [0]*len(T)
while start<len(T)-1:
first+=1
if T[first]>T[start]:
res[start]=(first-start)
start+=1
first = start
if first==len(T)-1:
start+=1
first = start
return res | daily-temperatures | [Python] | Need Suggestions to improve complexity?? | rachitsxn292 | 0 | 155 | daily temperatures | 739 | 0.666 | Medium | 12,110 |
https://leetcode.com/problems/daily-temperatures/discuss/343443/Python-3-self-explanatory-solution | class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
l=len(T)
res=[0]*l
stack=[(T[0],0)]
i=1
while stack and i<l:
while stack and T[i]>stack[-1][0]:
res[stack[-1][1]]=i-stack[-1][1]
stack.pop()
stack.append((T[i],i))
i+=1
return res | daily-temperatures | Python 3 self explanatory solution | ketan35 | 0 | 439 | daily temperatures | 739 | 0.666 | Medium | 12,111 |
https://leetcode.com/problems/daily-temperatures/discuss/1435642/Python-Clean | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
N = len(temperatures)
stack, answer = [], [0 for _ in range(N)]
for index, value in enumerate(temperatures):
while stack and stack[-1][1] < value:
i = stack.pop()[0]
answer[i] = index-i
stack.append((index, value))
return answer | daily-temperatures | [Python] Clean | 111989 | -1 | 175 | daily temperatures | 739 | 0.666 | Medium | 12,112 |
https://leetcode.com/problems/delete-and-earn/discuss/916859/Python3-top-down-dp | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
mp = {}
for x in nums: mp[x] = x + mp.get(x, 0)
@lru_cache(None)
def fn(i):
"""Return maximum points one can earn from nums[i:]."""
if i >= len(nums): return 0
if nums[i] + 1 not in mp: return mp[nums[i]] + fn(i+1)
return max(mp[nums[i]] + fn(i+2), fn(i+1))
nums = sorted(set(nums))
return fn(0) | delete-and-earn | [Python3] top-down dp | ye15 | 7 | 273 | delete and earn | 740 | 0.573 | Medium | 12,113 |
https://leetcode.com/problems/delete-and-earn/discuss/916859/Python3-top-down-dp | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
freq = Counter(nums)
prev = -inf
f0 = f1 = 0
for x in sorted(freq):
if prev + 1 == x: f0, f1 = max(f0, f1), f0 + x*freq[x]
else: f0, f1 = max(f0, f1), max(f0, f1) + x*freq[x]
prev = x
return max(f0, f1) | delete-and-earn | [Python3] top-down dp | ye15 | 7 | 273 | delete and earn | 740 | 0.573 | Medium | 12,114 |
https://leetcode.com/problems/delete-and-earn/discuss/2438160/Python-Solution-O(n)-similar-to-House-Robber-Faster-than-89.94-solutions | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
# createed a dic to store value of a number i.e the dic[n] = n*(number of times it occurs)
dic = defaultdict(int)
for n in nums:
dic[n] += n
# made a list of unique num in nums, OR -> made a list so we can use it as House Robber
newList = list(set(nums))
newList.sort()
# point list contains all the indexes in newList where the difference between any two consicutive num is greater than 1.
# newList = [2,3,4,6,7,8,11,12] then -> point = [3,6] + ( also append len(newList)) to process the last 11,12 as we did in House Robber.
# points = [3,6,8]
point = []
N = len(newList)
for i in range(1,N):
if newList[i] - newList[i-1] > 1:
point.append(i)
if len(point)==0 or point[-1] != N:
point.append(N)
# similar to House Robber. We try to get maximum for each sub array.
# [2,3,4] , [6,7,8] , [11,12] ( prev = 0 )
earning,prev = 0,0 # earning = 0, prev = 0 ( index starting)
for indx in point: # points = # points = [3,6,8].. for each index we want to calculate max contiribution of it subarray... [0,3], [3,6], [6,8]
dp = [-10**20,-10**20]
for i,n in enumerate(newList[prev:indx]): # lists -> [2,3,4] , [6,7,8] , [11,12]
if i == 0: # BASE CONDITION
dp[0] = max(dp[0], dic[n])
continue
if i == 1: # BASE CONDITION
dp[1] = max(dp[1], dic[n])
continue
# UPDATING VALUES
temp = dp[1]
dp[1] = max(dic[n], dp[0]+dic[n],dp[1])
dp[0] = max(temp,dp[0])
earning += max(dp) # updating earings
prev = indx #prev updated to 3,6,8 after subarrays
return earning # FINAL ANSWER | delete-and-earn | Python Solution O(n) similar to House Robber Faster than 89.94% solutions | notxkaran | 4 | 393 | delete and earn | 740 | 0.573 | Medium | 12,115 |
https://leetcode.com/problems/delete-and-earn/discuss/2438160/Python-Solution-O(n)-similar-to-House-Robber-Faster-than-89.94-solutions | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
# c
dic = defaultdict(int)
for n in nums:
dic[n] += n
newList = list(set(nums))
newList.sort()
point = []
N = len(newList)
for i in range(1,N):
if newList[i] - newList[i-1] > 1:
point.append(i)
if len(point)==0 or point[-1] != N:
point.append(N)
earning,prev = 0,0
for indx in point:
dp = [-10**20,-10**20]
for i,n in enumerate(newList[prev:indx]):
if i == 0:
dp[0] = max(dp[0], dic[n])
continue
if i == 1:
dp[1] = max(dp[1], dic[n])
continue
temp = dp[1]
dp[1] = max(dic[n], dp[0]+dic[n],dp[1])
dp[0] = max(temp,dp[0])
earning += max(dp)
prev = indx
return earning | delete-and-earn | Python Solution O(n) similar to House Robber Faster than 89.94% solutions | notxkaran | 4 | 393 | delete and earn | 740 | 0.573 | Medium | 12,116 |
https://leetcode.com/problems/delete-and-earn/discuss/1820848/Python-3-or-DP-Greedy-O(NLogN)-House-Robber-or-Explanation | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
c = collections.Counter(nums)
keys = sorted(c.keys())
prev = 0
ans = cur = c[keys[0]] * keys[0]
for i in range(1, len(keys)):
if keys[i] == keys[i-1] + 1:
prev, cur = cur, max(cur, prev + keys[i] * c[keys[i]])
else:
prev, cur = cur, cur + keys[i] * c[keys[i]]
ans = max(ans, cur)
return ans | delete-and-earn | Python 3 | DP, Greedy, O(NLogN), House Robber | Explanation | idontknoooo | 4 | 522 | delete and earn | 740 | 0.573 | Medium | 12,117 |
https://leetcode.com/problems/delete-and-earn/discuss/1666434/Delete-and-Earn-greater-House-Robber-variation-DP-bottom-up | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
gold_houses = [0] * max(nums)
for num in nums:
gold_houses[num-1] += num
# below is the House Robber question, with gold_houses as the input
# recurrence relation: max_points(i) = max(nums[i] + max_points(i-2), max_points(i-1))
max_gold_i_minus_1, max_gold_i_minus_2 = 0, 0
for gold in gold_houses:
max_gold_i = max(gold + max_gold_i_minus_2, max_gold_i_minus_1)
max_gold_i_minus_1, max_gold_i_minus_2 = max_gold_i, max_gold_i_minus_1
return max_gold_i | delete-and-earn | Delete and Earn --> House Robber variation; DP bottom-up | NinjaBlack | 3 | 155 | delete and earn | 740 | 0.573 | Medium | 12,118 |
https://leetcode.com/problems/delete-and-earn/discuss/1666434/Delete-and-Earn-greater-House-Robber-variation-DP-bottom-up | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
gold = [0] * (max(nums)+1)
for num in nums:
gold[num] += num
g0, g1 = 0, 0
for i in range(1, len(gold)):
g1, g0 = max(gold[i] + g0, g1), g1
return g1 | delete-and-earn | Delete and Earn --> House Robber variation; DP bottom-up | NinjaBlack | 3 | 155 | delete and earn | 740 | 0.573 | Medium | 12,119 |
https://leetcode.com/problems/delete-and-earn/discuss/1541098/Python-Easy-House-Robber-variation | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
d = [0]*(max(nums) + 1)
for i in nums:
d[i] += i
p2, p1 = 0, 0
for i in range(len(d)):
p1, p2 = max(d[i]+p2, p1), p1
return max(p1, p2) | delete-and-earn | [Python] Easy , House Robber variation | lokeshsenthilkumar | 3 | 273 | delete and earn | 740 | 0.573 | Medium | 12,120 |
https://leetcode.com/problems/delete-and-earn/discuss/1189565/Well-Explained-(with-example)-oror-Python-oror-96-faster-oror-DP-oror-O(nlogn) | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
m=max(nums)
dic=Counter(nums)
dp=[0]*(m+1)
for k in dic:
dp[k]=k*dic[k]
for i in range(2,m+1):
dp[i]=max(dp[i-1], dp[i-2]+ dp[i])
return dp[-1] | delete-and-earn | Well-Explained (with example) || Python || 96% faster || DP || O(nlogn) | abhi9Rai | 3 | 263 | delete and earn | 740 | 0.573 | Medium | 12,121 |
https://leetcode.com/problems/delete-and-earn/discuss/2394588/python-oror-dp-oror-top-down-oror-recursion-oror-memoization | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
count = Counter(nums)
m = max(nums)
memo = {}
def choose(num):
if num > m:
return 0
if num not in count:
count[num] = 0
if num in memo:
return memo[num]
memo[num] = max(choose(num + 1), num * count[num] + choose(num + 2))
return memo[num]
return choose(1)
# time and space complexity
# n = max(nums)
# time: O(n)
# space: O(n) | delete-and-earn | python || dp || top down || recursion || memoization | Yared_betsega | 2 | 134 | delete and earn | 740 | 0.573 | Medium | 12,122 |
https://leetcode.com/problems/delete-and-earn/discuss/1475424/PyPy3-Solution-using-House-Robber-Part-1-Logic-w-comments | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
# Frequency of numbers
freq = [0] * (max(nums)+1)
for num in nums:
freq[num] += num
# House Robber Problem from here on
# apply house robber logic on freq array
# Init
f = len(freq)
# Base Case
if f == 0:
return 0
# Base Case
if f <= 2:
return max(freq)
# Init
t = dict()
t[0] = freq[0]
t[1] = max(freq[0], freq[1])
# DP: either you can take this element
# and add it to the subproblem i-2 steps
# before it, or you take subproblem i-1 steps
# before it
for i in range(2,f):
t[i] = max(t[i-1], freq[i] + t[i-2])
return t[f-1] | delete-and-earn | [Py/Py3] Solution using House Robber Part 1 Logic w/ comments | ssshukla26 | 2 | 219 | delete and earn | 740 | 0.573 | Medium | 12,123 |
https://leetcode.com/problems/delete-and-earn/discuss/1323959/better-than-99.95 | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
dict=Counter(nums)
m=max(nums)
dp=[0]*(m+1)
for i in range(1,m+1):
if i in dict:
if i==1:
dp[i]=dict[i]*i
else:
dp[i]=max(dp[i-1],dp[i-2]+i*dict[i])
else:
dp[i]=dp[i-1]
return dp[-1] | delete-and-earn | better than 99.95% | pramodh18 | 2 | 204 | delete and earn | 740 | 0.573 | Medium | 12,124 |
https://leetcode.com/problems/delete-and-earn/discuss/2480368/Python-DP-Solution-with-DP | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
points = defaultdict(lambda:0)
max_number = max(nums)
points = Counter(nums)
max_points = [0] * (max_number + 2)
for num in range(len(max_points)):
max_points[num] = max(max_points[num - 1], max_points[num - 2] + points[num] * num)
return max_points[max_number] | delete-and-earn | Python DP Solution with DP | Xiang-Pan | 1 | 114 | delete and earn | 740 | 0.573 | Medium | 12,125 |
https://leetcode.com/problems/delete-and-earn/discuss/2104026/Python3-or-DP-or-Easy-Understand | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
counter = Counter(nums)
max_n = max(nums)
dp = [0] * (max_n + 1)
dp[1] = counter[1]
for i in range(2, max_n + 1):
dp[i] = max(dp[i-1], dp[i-2] + counter[i] * i)
return dp[-1] | delete-and-earn | Python3 | DP | Easy-Understand | Yilin_Bai | 1 | 92 | delete and earn | 740 | 0.573 | Medium | 12,126 |
https://leetcode.com/problems/delete-and-earn/discuss/1822613/Simple-Python3-Solution | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
maps = Counter(nums)
nums = sorted(list(set(nums)))
prev = prevprev = 0
for i,num in enumerate(nums):
currPoint = num*maps[num]
tmp=prev
if i>0 and num==nums[i-1]+1:
prev=max(prev,prevprev+currPoint)
else:
prev+=currPoint
prevprev=tmp
return prev | delete-and-earn | Simple Python3 Solution | user6774u | 1 | 67 | delete and earn | 740 | 0.573 | Medium | 12,127 |
https://leetcode.com/problems/delete-and-earn/discuss/1821143/Super-Easy-Super-Optimized | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
dict1=dict()
dp=[0]*(max(nums)+1)
for i in nums:
dict1[i]=dict1.get(i,0)+i
for i in range(1,max(nums)+1):
dp[i]=max(dp[i-1],dict1.get(i,0)+dp[i-2])
return dp[-1] | delete-and-earn | Super Easy, Super Optimized | vedank98 | 1 | 77 | delete and earn | 740 | 0.573 | Medium | 12,128 |
https://leetcode.com/problems/delete-and-earn/discuss/1820399/DP-oror-House-Robber-Variation | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
points = [0] * (max(nums)+1)
for num in nums:
points[num] += num
previous = points[0]
current = points[1]
for idx in range(2,len(points)):
current, previous = max(current, previous + points[idx]), current
return current
O(N) space and time N : max element in array. | delete-and-earn | DP || House Robber Variation | beginne__r | 1 | 34 | delete and earn | 740 | 0.573 | Medium | 12,129 |
https://leetcode.com/problems/delete-and-earn/discuss/1764708/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
nums_counter = Counter(nums)
prev = -1
avoid = using = 0
for i in sorted(nums_counter):
if i - 1 != prev:
avoid, using = max(avoid, using), i * \
nums_counter[i] + max(avoid, using)
else:
avoid, using = max(avoid, using), i*nums_counter[i]+avoid
prev = i
return max(avoid, using) | delete-and-earn | ✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 1 | 153 | delete and earn | 740 | 0.573 | Medium | 12,130 |
https://leetcode.com/problems/delete-and-earn/discuss/1764708/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
memo = {}
counter = Counter(nums)
sorted_nums = sorted(counter)
def dp(i: int) -> int:
if i == 0:
return sorted_nums[0]*counter[sorted_nums[0]]
if i == 1:
if sorted_nums[1] == sorted_nums[0]+1:
return max(sorted_nums[0]*counter[sorted_nums[0]], sorted_nums[1]*counter[sorted_nums[1]])
else:
return sorted_nums[0]*counter[sorted_nums[0]]+sorted_nums[1]*counter[sorted_nums[1]]
if i not in memo:
if sorted_nums[i-1] == sorted_nums[i]-1:
memo[i] = max(
sorted_nums[i]*counter[sorted_nums[i]]+dp(i-2), dp(i-1))
else:
memo[i] = sorted_nums[i] * \
counter[sorted_nums[i]]+dp(i-1)
return memo[i]
return dp(len(sorted_nums)-1) | delete-and-earn | ✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 1 | 153 | delete and earn | 740 | 0.573 | Medium | 12,131 |
https://leetcode.com/problems/delete-and-earn/discuss/1716577/Python-4-Approaches-or-Brute-Force-to-Optimal-or-Time-and-Space-Complexity | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
def helper(ind,nums):
if ind==0:
return nums[0]
if ind<0:
return 0
#TAKE
take=nums[ind]+helper(ind-2,nums)
#NOT TAKE
not_take=helper(ind-1,nums)
return max(take,not_take)
def delete_and_earn(nums):
maxi=max(nums)
count=[0]*(maxi+1)
for num in nums:
count[num]+=num
n=len(count)
return helper(n-1,count)
return delete_and_earn(nums) | delete-and-earn | Python 4 Approaches | Brute Force to Optimal | Time and Space Complexity | aryanagrawal2310 | 1 | 283 | delete and earn | 740 | 0.573 | Medium | 12,132 |
https://leetcode.com/problems/delete-and-earn/discuss/1716577/Python-4-Approaches-or-Brute-Force-to-Optimal-or-Time-and-Space-Complexity | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
def helper(ind,nums,dp):
if ind==0:
return nums[0]
if ind<0:
return 0
if dp[ind]!=-1:
return dp[ind]
#TAKE
take=nums[ind]+helper(ind-2,nums,dp)
#NOT TAKE
not_take=helper(ind-1,nums,dp)
dp[ind]=max(take,not_take)
return dp[ind]
def delete_and_earn(nums):
maxi=max(nums)
count=[0]*(maxi+1)
for num in nums:
count[num]+=num
n=len(count)
dp=[-1]*n
return helper(n-1,count,dp)
return delete_and_earn(nums) | delete-and-earn | Python 4 Approaches | Brute Force to Optimal | Time and Space Complexity | aryanagrawal2310 | 1 | 283 | delete and earn | 740 | 0.573 | Medium | 12,133 |
https://leetcode.com/problems/delete-and-earn/discuss/1716577/Python-4-Approaches-or-Brute-Force-to-Optimal-or-Time-and-Space-Complexity | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
def helper(arr):
n=len(arr)
dp=[-1]*(n)
dp[0]=arr[0]
for i in range(1,n):
first=dp[i-1]
second=arr[i]
if i>1:
second=arr[i]+dp[i-2]
dp[i]=max(first,second)
return dp[n-1]
def delete_and_earn(nums):
maxi=max(nums)
count=[0]*(maxi+1)
for num in nums:
count[num]+=num
return helper(count)
return delete_and_earn(nums) | delete-and-earn | Python 4 Approaches | Brute Force to Optimal | Time and Space Complexity | aryanagrawal2310 | 1 | 283 | delete and earn | 740 | 0.573 | Medium | 12,134 |
https://leetcode.com/problems/delete-and-earn/discuss/1716577/Python-4-Approaches-or-Brute-Force-to-Optimal-or-Time-and-Space-Complexity | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
def helper(arr):
n=len(arr)
prev2=0
prev=arr[0]
for i in range(1,n):
ans=max(prev,prev2+arr[i])
prev2=prev
prev=ans
return prev
def delete_and_earn(nums):
maxi=max(nums)
count=[0]*(maxi+1)
for num in nums:
count[num]+=num
return helper(count)
return delete_and_earn(nums) | delete-and-earn | Python 4 Approaches | Brute Force to Optimal | Time and Space Complexity | aryanagrawal2310 | 1 | 283 | delete and earn | 740 | 0.573 | Medium | 12,135 |
https://leetcode.com/problems/delete-and-earn/discuss/1628981/Python3-oror-Dynamic-Programming-oror-O(nlogn)-time-complexity | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
occurences = dict()
for i in nums:
if i in occurences:
occurences[i] += 1
else:
occurences[i] = 1
#remove repeating elements and sort
nums = list(set(nums))
nums.sort()
first = nums[0] * occurences[nums[0]]
if nums[1] - nums[0] == 1:
#we can't include the previous element
second = max(first,nums[1] * occurences[nums[1]])
else:
second = first + nums[1] * occurences[nums[1]]
dp = [0] * len(nums)
dp[0] = first
dp[1] = second
for i in range(2,len(dp)):
if nums[i] - nums[i-1] == 1:
# we can't include nums[i-1], we'll include nums[i]
dp[i] = max(dp[i-2] + nums[i] * occurences[nums[i]],dp[i-1])
else:
dp[i] = dp[i-1]+ nums[i] * occurences[nums[i]]
return dp[-1] | delete-and-earn | Python3 || Dynamic Programming || O(nlogn) time complexity | s_m_d_29 | 1 | 239 | delete and earn | 740 | 0.573 | Medium | 12,136 |
https://leetcode.com/problems/delete-and-earn/discuss/1562760/Python3-solution-97.44-faster | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
maximum: int = max(nums)
count: List[int] = [0] * (maximum + 1)
for num in nums:
count[num] += num
previous: int = 0
current: int = 0
for i in range(0, len(count)):
previous, current = current, max(previous + count[i], current)
return current | delete-and-earn | Python3 solution 97.44% faster | sirenescx | 1 | 308 | delete and earn | 740 | 0.573 | Medium | 12,137 |
https://leetcode.com/problems/delete-and-earn/discuss/1512397/Any-optimisation-suggestions | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
if len(set(nums)) == 1: return sum(nums)
count = dict(collections.Counter(sorted(nums)))
num, freq = [], []
for i, j in count.items():
num.append(i)
freq.append(j)
dp = [0]*len(num)
dp[0] = num[0]*freq[0]
if num[1] - 1 in num: dp[1] = max(dp[0], num[1]*freq[1])
else: dp[1] = dp[0] + (num[1]*freq[1])
for i in range(2, len(num)):
if num[i]-1 in num: dp[i] = max(dp[i-1], (num[i]*freq[i])+dp[i-2])
else: dp[i] = dp[i-1] + (num[i]*freq[i])
return dp[-1] | delete-and-earn | Any optimisation suggestions ?? | siddp6 | 1 | 422 | delete and earn | 740 | 0.573 | Medium | 12,138 |
https://leetcode.com/problems/delete-and-earn/discuss/1467110/python-O(n)-time-O(n)-space-solution-no-sorting | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
count = defaultdict(int)
for num in nums:
count[num] += 1
dp = [0 for _ in range(max(nums) + 1)]
for k in count:
dp[k] = k*count[k]
def rob(nums: List[int]) -> int:
n = len(nums)
if n == 1:
return nums[0]
elif n ==2:
return max(nums[0], nums[1])
elif n== 3:
return max(nums[0]+nums[2], nums[1])
a = nums[0]
b = nums[1]
c = nums[0] + nums[2]
maxv = max(a, b, c)
for i in range(3, n):
d = nums[i] + max(a, b)
maxv = max(maxv, d)
a = b
b = c
c = d
return maxv
return rob(dp) | delete-and-earn | python O(n) time / O(n) space solution, no sorting | byuns9334 | 1 | 99 | delete and earn | 740 | 0.573 | Medium | 12,139 |
https://leetcode.com/problems/delete-and-earn/discuss/2822124/Python-Like-House-Robber-or-Track-Max-By-Adding-Last-OR-Max-of-Skipping-Last-or-Curr | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
# We get a hash map of counts and sort the values
counts = {}
for num in nums:
counts[num] = counts.get(num, 0) + 1
points = sorted(counts.keys())
'''
Rest is similar to House Robber series: https://leetcode.com/problems/house-robber/discuss/2821870/Python-Current-%2B-LastLast-OR-Last.-Rinse-and-Repeat-)
At every position, we track the max earned up to that point, where:
We start the earnings with current number * frequency (in counts map)
Then if the previous number is not 1 less than current, add it
Otherwise, take the maximum
of current + last-last (skipping last)
or just the last (skipping current and taking the max up to last)
'''
last_last, last = 0, 0
for i in range(len(points)):
earned = (points[i] * counts[points[i]])
if i > 0 and points[i] == points[i-1] + 1:
earned = max(earned + last_last, last)
else:
earned += last
last_last, last = last, earned
return last | delete-and-earn | [Python] Like House Robber | Track Max By Adding Last OR Max of Skipping Last or Curr | graceiscoding | 0 | 2 | delete and earn | 740 | 0.573 | Medium | 12,140 |
https://leetcode.com/problems/delete-and-earn/discuss/2711752/Python-DP-solution | class Solution:
def deleteAndEarn(self, arr: List[int]) -> int:
arr = sorted(arr)[::-1]
uniq = [arr[0]]
for i in range(1, len(arr)):
if arr[i] != arr[i - 1]:
uniq.append(arr[i])
hm = dict(Counter(arr))
d = [-1] * len(uniq)
def dp(i):
if i >= len(uniq):
return 0
if d[i] != -1:
return d[i]
if uniq[i] - 1 not in hm:
d[i] = hm[uniq[i]] * uniq[i] + dp(i + 1)
else:
d[i] = max(dp(i + 1), hm[uniq[i]] * uniq[i] + dp(i + 2))
return d[i]
dp(0)
return d[0] | delete-and-earn | Python DP solution | JSTM2022 | 0 | 5 | delete and earn | 740 | 0.573 | Medium | 12,141 |
https://leetcode.com/problems/delete-and-earn/discuss/2702659/Easy-to-understand-Python-DP-solution-based-on-House-Robber | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
count = collections.Counter(nums)
dp = [0]*(max(nums)+1) #max len is 10001
#base cases
dp[0] = 0*count[0]
dp[1] = 1*count[1]
for i in range(2, len(dp)):
#recurrence relation
dp[i] = max(i*count[i] + dp[i-2], dp[i-1])
return dp[-1] | delete-and-earn | Easy to understand Python DP solution based on House Robber | sc1233 | 0 | 9 | delete and earn | 740 | 0.573 | Medium | 12,142 |
https://leetcode.com/problems/delete-and-earn/discuss/2686768/python-working-solution-or-dp-or-memoization | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
d= {}
for i in nums:
d[i] = 1 + d.get(i,0)
l = list(d.keys())
l.sort()
dp = {}
def dfs(i,s):
if i>=len(l):
return 0
if l[i] in s:
return dfs(i+1,s)
if i in dp:
return dp[i]
s.add(l[i]+1)
k = (l[i] * d[l[i]]) + dfs(i+1,s)
s.remove(l[i]+1)
dp[i] = max(k , dfs(i+1,s))
return dp[i]
return dfs(0,set()) | delete-and-earn | python working solution | dp | memoization | Sayyad-Abdul-Latif | 0 | 19 | delete and earn | 740 | 0.573 | Medium | 12,143 |
https://leetcode.com/problems/delete-and-earn/discuss/2681690/Python-oror-Memoization-Solution-oror-93.77-Faster | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
n = len(nums)
m = max(nums)
# arr is used to store count of each element in nums with respect to index
arr = [0 for i in range(m+1)]
dp = [-1 for i in range(m+1)]
for i in range(len(nums)):
arr[nums[i]] += 1
# Memoization Solution
def helper(index):
nonlocal m
if index > m:
return 0
if dp[index] != -1:
return dp[index]
pick = 0
if arr[index] > 0:
pick = arr[index] * index + helper(index+2)
notpick = helper(index+1)
dp[index] = max(pick, notpick)
return max(pick, notpick)
# ans1 indicates if we start from 1st element
ans1 = helper(1)
# ans2 indicates if we start from 2nd element
ans2 = helper(2)
return max(ans1, ans2) | delete-and-earn | Python || Memoization Solution || 93.77% Faster | shreya_pattewar | 0 | 9 | delete and earn | 740 | 0.573 | Medium | 12,144 |
https://leetcode.com/problems/delete-and-earn/discuss/2665074/Python-or-O(n)-solution-with-comments | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
# First step is simple count sort
stat = [0]*(10**4 + 1)
for num in nums:
stat[num] += 1
# For second step we use dynamic programming approach
# We can either choose previous value or pre-previous value plus value from count array
dp = [0]*(10**4 + 1)
dp[1] = stat[1]
for i in range(2, 10**4 + 1):
dp[i] = max(dp[i - 1], dp[i - 2] + stat[i]*i)
return dp[-1] | delete-and-earn | Python | O(n) solution with comments | LordVader1 | 0 | 22 | delete and earn | 740 | 0.573 | Medium | 12,145 |
https://leetcode.com/problems/delete-and-earn/discuss/2458019/python3-easy-solution-(change-to-leetcode-198) | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
house=[]
temp=0
nums.sort()
for i in range(len(nums)): #create house list, nums[i] as index of house
if i!=len(nums)-1:
if nums[i]==nums[i+1]:
temp+=nums[i]
else:
temp+=nums[i]
house.append(temp)
temp=0
for j in range(nums[i+1]-nums[i]-1):
house.append(0)
else:
temp+=nums[i]
house.append(temp)
@cache
def dp(n :int) -> int:
if n<0:
return 0
return max(house[n]+dp(n-2),dp(n-1))
return dp(len(house)-1) | delete-and-earn | python3 easy solution (change to leetcode 198) | kyoko0810 | 0 | 94 | delete and earn | 740 | 0.573 | Medium | 12,146 |
https://leetcode.com/problems/delete-and-earn/discuss/2413530/Python3-or-Can't-Figure-Out-Bug-in-My-Bottom-UP-DP-Code | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
#if you think about this problem recursively, basically this problem exhibits both
#optimal substructure property as well as overlapping subproblems!
#For example, let's take first test case!
#nums = [3, 4, 2]
#Draw out rec. tree!
# [3, 4, 2]
#. /. |. \
#. 3. 4. 2
#. /. |. \
#. [] [2] [4]
#. | \
#. 2 4
#. | \
#. [] []
#basically, every edge represents the number I choose to delete to get points!
#You can see that the remaining elements in the array compose each and every subproblem!
#If you notice, for any given subproblem, if you know the maximized points you can get
#from deleting each and every distinct integer that appears in that given subproblem array,
#then, you can take each of those subproblem results' and add the edge value and get the max across!
#this will be the answer -> Solving subproblems optimally leads to optimal overall solution!(Optimal
#substructure property)
#Clearly, there is possibility of subarrays of original array of numbers being considered
#multiple times across different places in rec. tree! -> Possibility of overlapping subproblems!
#I'll try solving bottom-up this time!
#Here, the state paramter is only going to be index position i!
#Since our input array is allowed to have duplicates, we will simply the array we are
#traversing by removing any duplicates and have frequency count info stored in hashmap!
hashmap = {}
for num in nums:
if num not in hashmap:
hashmap[num] = 1
else:
hashmap[num] += 1
distinct = list(set(nums))
#dp table: store the maximized points I can get for elements up to index i if I choose
#to delete index i for points!
if(len(distinct) == 1):
return distinct[0] * hashmap[distinct[0]]
n = len(distinct)
dp = [0] * n
#we have to sort the array of distinct numbers so that we can check for any index i, if the previous element
#is 1 less in value -> If that's the case, we just delete it and not take its value into account for points!
distinct.sort()
#add the dp base case
dp[0] = distinct[0] * hashmap[distinct[0]]
dp[1] = (distinct[1] * hashmap[distinct[1]]) + dp[0] if distinct[1] - 1 != distinct[0] else distinct[1] * hashmap[distinct[1]]
#iterate through subproblems or state paramter i!
for i in range(2, n):
#if the previous number is not equal to nums[i] - 1, then max. points we can get for
#all elements up to index i is going to be maximized points up to index i-1, if we delete
#nums[i-1] + nums[i]
cur = distinct[i]
cur_freq = hashmap[cur]
dp[i] = (cur * cur_freq) + dp[i-1] if distinct[i-1] != cur - 1 else (cur * cur_freq + dp[i-2])
return dp[n-1] | delete-and-earn | Python3 | Can't Figure Out Bug in My Bottom-UP DP Code | JOON1234 | 0 | 15 | delete and earn | 740 | 0.573 | Medium | 12,147 |
https://leetcode.com/problems/delete-and-earn/discuss/2413109/Python3-or-Question-on-Top-Down-Approach%3A-How-to-Memo-Array-Instances! | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
#if you think about this problem recursively, basically this problem exhibits both
#optimal substructure property as well as overlapping subproblems!
#For example, let's take first test case!
#nums = [3, 4, 2]
#Draw out rec. tree!
# [3, 4, 2]
#. /. |. \
#. 3. 4. 2
#. /. |. \
#. [] [2] [4]
#. | \
#. 2 4
#. | \
#. [] []
#basically, every edge represents the number I choose to delete to get points!
#You can see that the remaining elements in the array compose each and every subproblem!
#If you notice, for any given subproblem, if you know the maximized points you can get
#from deleting each and every distinct integer that appears in that given subproblem array,
#then, you can take each of those subproblem results' and add the edge value and get the max across!
#this will be the answer -> Solving subproblems optimally leads to optimal overall solution!(Optimal
#substructure property)
#Clearly, there is possibility of subarrays of original array of numbers being considered multiple times
#across different places in rec. tree! -> Possibility of overlapping subproblems!
hashmap = {}
for num in nums:
if(num not in hashmap):
hashmap[num] = 1
else:
hashmap[num] += 1
def helper(arr, d):
#Try implementing top down dp approach!
#base case: array with just 1 element -> go delete that element and get the points!
if(len(arr) == 1):
return arr[0]
#let s represent set of distinct numbers present in nums arr!
s = set(arr)
#for each and every number in set s, we consider all remaining elements as arr, recurse on #it and add the element in s we are currently iterating on, element we remove and get points #for! Take the max across all possible paths spanning from current subproblem dedicated to #arr!
ans = 0
for e in s:
copy = d.copy()
#we delete element e so it appears 1 less in rem. elements!
if(copy[e] == 1):
copy.pop(e)
else:
copy[e] -= 1
#remove e+1 and e-1 numbers as keys from dictionary!
if(e+1 in copy):
#save original key value pair before removing it b/c we need it for next iteration!
copy.pop(e + 1)
if(e-1 in copy):
copy.pop(e - 1)
#once we have correct remaining numbers and their freq. count in dictionary d,
#iterate through each key-value pair and put their elements in one overall arr
#to recurse on!
overall_arr = []
#copy dict should tell what are rem distinct numbers and their each freq. count!
for k,v in copy.items():
overall_arr = overall_arr + [k for _ in range(v)]
#pass along overall_arr, which is remaining numbers in rec. call along with
#current state of copy!
#update answer if the recursive call result + element e value we get as points
#for removing exceeds current ans!
ans = max(ans,helper(overall_arr, copy) + e)
#restore the original state of dictionary before next iteration of for loop!
return ans
return helper(nums, hashmap) | delete-and-earn | Python3 | Question on Top-Down Approach: How to Memo Array Instances! | JOON1234 | 0 | 31 | delete and earn | 740 | 0.573 | Medium | 12,148 |
https://leetcode.com/problems/delete-and-earn/discuss/2305019/Python-DP-easy | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
count = collections.Counter(nums)
nums = sorted(set(nums))
n = len(count)
dp = [0]*n
dp[0] = nums[0]*count[nums[0]]
print(nums)
for i in range(1,n):
if nums[i] -1 == nums[i-1]:
dp[i] = max(nums[i]*count[nums[i]]+dp[i-2], dp[i-1])
else:
dp[i] = nums[i]*count[nums[i]]+dp[i-1]
return dp[-1] | delete-and-earn | Python DP easy | Abhi_009 | 0 | 79 | delete and earn | 740 | 0.573 | Medium | 12,149 |
https://leetcode.com/problems/delete-and-earn/discuss/1941502/Python3-oror-Bottom-Up-Solution | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
max_val = max(nums)
dp = [0] * ( max_val + 1 )
for i in nums :
dp[i] += i
for i in range(2,len(dp)):
dp[i] = max(dp[i-1],dp[i] + dp[i-2])
return dp[max_val] | delete-and-earn | Python3 || Bottom Up Solution | subhamsubhasispatra | 0 | 151 | delete and earn | 740 | 0.573 | Medium | 12,150 |
https://leetcode.com/problems/delete-and-earn/discuss/1821905/Python-easy-and-clean-solution-or-Explained | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
dic, prev = defaultdict(int), -1
prevMax = leftMax = 0 # prevMax: maximum till the previous, leftMax: maximum just before the prevous
for i in nums: dic[i] += 1 # counting the frequency
get = lambda i: i * dic.get(i, 0) # I took this for better readability, it will return the product of the number and its frequency
for i in sorted(dic): # traversing the sorted dictionary, sorting is used because smaller values must be processed first.
temp = prevMax # prevMax value will change but we need that value to update the leftMax.
if i - 1 == prev: prevMax = max(prevMax ,get(i) + leftMax) # important point: if i - 1 is equal to prev, it is obvious that prevMax was calculated with the help of i-1, and we can't add it, so we will add leftMax beacuse leftMax is not caculated with the help of i-1, then we calculate the maximum out of it.
else: prevMax = get(i) + prevMax # if they are not equal, we have no issue in adding the prevMax.
leftMax = temp # update the leftMax to temp
prev = i # upadte the prev, so that we remember prevMax was calculated with this i
return prevMax | delete-and-earn | ✅ Python easy and clean solution | Explained | dhananjay79 | 0 | 70 | delete and earn | 740 | 0.573 | Medium | 12,151 |
https://leetcode.com/problems/delete-and-earn/discuss/1821397/Python3-Dynamic-Programming-Bottom-Up-Approach | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
d=Counter(nums)
N = len(d)
temp = [[None]*2 for _ in range(N+1)]
# Base case
temp[0][0]=0 # j=0 --> Exclude
temp[0][1]=0 # j=1 --> Include
# Choice diagram
# Traverse dict instead of array
keys = list(d.keys())
keys.sort()
for i in range(1,N+1):
for j in range(2):
if j==0: # If you wanna exclude take max(prev_include,prev_exclude)
temp[i][j] = max(temp[i-1][0],temp[i-1][1])
if j==1: # If you wanna include
if i==0: # Blind include(as it is first element)
temp[i][j] = keys[i-1]*d[keys[i-1]]
else: # check if curr_element is consecutive to prev_element
if keys[i-1]==keys[i-2]+1: # If yes,consider prev_exclude + curr_element
temp[i][j] = temp[i-1][0]+keys[i-1]*d[keys[i-1]]
else: # Consider max(prev_include,prev_exclude)+curr_element
temp[i][j] = max(temp[i-1][0],temp[i-1][1])+keys[i-1]*d[keys[i-1]]
return max(temp[-1]) | delete-and-earn | Python3 Dynamic Programming Bottom Up Approach | KiranRaghavendra | 0 | 39 | delete and earn | 740 | 0.573 | Medium | 12,152 |
https://leetcode.com/problems/delete-and-earn/discuss/1820561/Python-Simple-Python-Solution-Using-Dynamic-Programming-and-Dictionary | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
count_frequency = defaultdict(int)
max_number = max(nums)
for num in nums:
count_frequency[num] = count_frequency[num] + num
dp = [0]*(max_number + 1)
dp[1] = count_frequency[1]
for j in range(2,len(dp)):
dp[j] = max(dp[j-1], dp[j-2] + count_frequency[j])
return dp[max_number] | delete-and-earn | [ Python ] ✔✔ Simple Python Solution Using Dynamic Programming and Dictionary 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 0 | 114 | delete and earn | 740 | 0.573 | Medium | 12,153 |
https://leetcode.com/problems/delete-and-earn/discuss/1792477/Easily-understanding-DP-solution-in-python-3 | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
cnt = [0] * (max(nums) + 1)
for num in nums:
cnt[num] += 1
# record the occurrence of each num
dp = [[0, 0] for i in range(max(nums)+1)]
res = 0
#Base case: dp[0][0], dp[0][1] = 0
for i in range(1, max(nums)+1):
# 0 means select the current num, 1 means not select
#F[i, 0] not select i: max(F(i-1, 0) F(i-1, 1))
#F[i, 1] select i: max(F(i - 2, 0), i*count(i))
dp[i][0] = max(dp[i-1][0], dp[i-1][1])
dp[i][1] = dp[i-1][0] + i*cnt[i]
res = max(res, max(dp[i][0], dp[i][1]))
return res | delete-and-earn | Easily understanding DP solution in python 3 | WhATEVERnameIS | 0 | 115 | delete and earn | 740 | 0.573 | Medium | 12,154 |
https://leetcode.com/problems/delete-and-earn/discuss/1771319/Python-easy-to-read-and-understand-or-DP | class Solution:
def solve(self, nums):
n = len(nums)
t = [[0 for _ in range(n)] for _ in range(2)]
t[0][0] = nums[0]
for i in range(1, n):
t[0][i] = t[1][i-1] + nums[i]
t[1][i] = max(t[0][i-1], t[1][i-1])
return max(t[0][n-1], t[1][n-1])
def deleteAndEarn(self, nums: List[int]) -> int:
d = {}
for num in nums:
d[num] = d.get(num, 0) + num
t = [0 for _ in range(max(nums)+1)]
for i in range(len(t)):
t[i] = d.get(i, 0)
return self.solve(t) | delete-and-earn | Python easy to read and understand | DP | sanial2001 | 0 | 131 | delete and earn | 740 | 0.573 | Medium | 12,155 |
https://leetcode.com/problems/delete-and-earn/discuss/1748290/Python-O(nlogn)-solution | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
sortedNums = sorted(nums)
aggr = {}
result = {}
prev = (0,0)
prev2 = (0,0)
for e in sortedNums:
aggr[e] = aggr.get(e, 0) + e
for key,val in aggr.items():
result[key] = max(result.get(key - 1, 0), result.get(key - 2, 0) + val, 0 if prev[0] == (key - 1) else prev[1] + val, prev2[1] + val)
prev2 = prev
prev = (key, result[key])
return result[key] | delete-and-earn | Python O(nlogn) solution | ganyue246 | 0 | 116 | delete and earn | 740 | 0.573 | Medium | 12,156 |
https://leetcode.com/problems/delete-and-earn/discuss/1592417/Python3-Iterative-dp-solution | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
count = collections.defaultdict(int)
_min, _max = float('inf'), float('-inf')
for num in nums:
count[num] += 1
_min = min(_min, num)
_max = max(_max, num)
cur = prev = 0
for i in range(_min, _max + 1):
prev, cur = cur, max(cur, prev + count[i] * i)
return cur | delete-and-earn | [Python3] Iterative dp solution | maosipov11 | 0 | 115 | delete and earn | 740 | 0.573 | Medium | 12,157 |
https://leetcode.com/problems/delete-and-earn/discuss/1460541/Easy-python-solutionoror-dict-and-dporor-Python3 | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
nums = sorted(nums,reverse=True)
dct = {}
for i in nums:
if i in dct:
dct[i]+=i
else:
dct[i] = i
lst = list(dct.keys())
dp = [0]*len(lst)
dp[0] = dct[lst[0]]
for i in range(1,len(lst)):
if lst[i] < lst[i-1]-1:
dp[i] = dp[i-1]+dct[lst[i]]
else:
dp[i] = max(dp[i-2]+dct[lst[i]],dp[i-1])
print(dp)
return dp[-1] | delete-and-earn | Easy python solution|| dict & dp|| Python3 | ce17b127 | 0 | 84 | delete and earn | 740 | 0.573 | Medium | 12,158 |
https://leetcode.com/problems/delete-and-earn/discuss/1422008/Python-Clean | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
if len(nums) == 1: return nums[0]
elif len(nums) == 2: return max(nums) if nums[0]+1 == nums[1] else sum(nums)
count = collections.Counter(nums)
elements = sorted(count.keys())
dp = [0]*len(elements)
dp[0] = elements[0]*count[elements[0]]
if elements[0]+1 == elements[1]: dp[1] = max(dp[0], elements[1]*count[elements[1]])
else: dp[1] = dp[0] + elements[1]*count[elements[1]]
for i in range(2, len(elements)):
if elements[i-1]+1 == elements[i]: dp[i] = max(dp[i-2] + elements[i]*count[elements[i]], dp[i-1])
else: dp[i] = dp[i-1] + elements[i]*count[elements[i]]
return dp[-1] | delete-and-earn | [Python] Clean | soma28 | 0 | 91 | delete and earn | 740 | 0.573 | Medium | 12,159 |
https://leetcode.com/problems/delete-and-earn/discuss/367890/Solution-in-Python-3-(beats-~100)-(four-lines) | class Solution:
def deleteAndEarn(self, n: List[int]) -> int:
if not n: return 0
a, b, C = 0, n.count(1), collections.Counter(n)
for i in range(2,max(n)+1): b, a = max(C[i]*i + a, b), b
return b
- Junaid Mansuri
(LeetCode ID)@hotmail.com | delete-and-earn | Solution in Python 3 (beats ~100%) (four lines) | junaidmansuri | 0 | 414 | delete and earn | 740 | 0.573 | Medium | 12,160 |
https://leetcode.com/problems/cherry-pickup/discuss/699169/Python3-dp | class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
n = len(grid)
@lru_cache(None)
def fn(t, i, ii):
"""Return maximum cherries collected at kth step when two robots are at ith and iith row"""
j, jj = t - i, t - ii #columns
if not (0 <= i < n and 0 <= j < n) or t < i or grid[ i][ j] == -1: return -inf #robot 1 not at proper location
if not (0 <= ii < n and 0 <= jj < n) or t < ii or grid[ii][jj] == -1: return -inf #robot 2 not at proper location
if t == 0: return grid[0][0] #starting from 0,0
return grid[i][j] + (i != ii)*grid[ii][jj] + max(fn(t-1, x, y) for x in (i-1, i) for y in (ii-1, ii))
return max(0, fn(2*n-2, n-1, n-1)) | cherry-pickup | [Python3] dp | ye15 | 2 | 241 | cherry pickup | 741 | 0.363 | Hard | 12,161 |
https://leetcode.com/problems/cherry-pickup/discuss/2798148/(Pythong)-Simplify-the-input-%3A-dp(x1-y1-x2)-with-%40cache | class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
@cache
def dp(x1, y1, x2):
y2 = x1+y1-x2
if not(0 <= x1 < len(grid) and 0 <= y1 < len(grid[0]) and 0 <= x2 < len(grid) and 0 <= y2 < len(grid[0])):
return -float('inf')
if grid[x1][y1] == -1 or grid [x2][y2] == -1 :
return -float('inf')
if x1 == len(grid)-1 and x2 == len(grid)-1 and y1 == len(grid[0])-1 and y1 == len(grid[0])-1 :
if grid[x1][y1] == 1 :
return 1
else :
return 0
if x1 == x2 and y1 == y2 :
if grid[x1][y1] == 1 :
return 1+max(dp(x1+1, y1, x2+1), dp(x1+1, y1, x2), dp(x1, y1+1, x2+1), dp(x1, y1+1, x2))
else:
return max(dp(x1+1, y1, x2+1), dp(x1+1, y1, x2), dp(x1, y1+1, x2+1), dp(x1, y1+1, x2))
else :
if grid[x1][y1] == 1 and grid[x2][y2] == 1:
return 2+max(dp(x1+1, y1, x2+1), dp(x1+1, y1, x2), dp(x1, y1+1, x2+1), dp(x1, y1+1, x2))
elif grid[x1][y1] == 1:
return 1+max(dp(x1+1, y1, x2+1), dp(x1+1, y1, x2), dp(x1, y1+1, x2+1), dp(x1, y1+1, x2))
elif grid[x2][y2] == 1:
return 1+max(dp(x1+1, y1, x2+1), dp(x1+1, y1, x2), dp(x1, y1+1, x2+1), dp(x1, y1+1, x2))
else:
return max(dp(x1+1, y1, x2+1), dp(x1+1, y1, x2), dp(x1, y1+1, x2+1), dp(x1, y1+1, x2))
if dp(0,0,0) == -float('inf'):
return 0
else :
return dp(0,0,0) | cherry-pickup | (Pythong) Simplify the input : dp(x1, y1, x2) with @cache | SooCho_i | 0 | 7 | cherry pickup | 741 | 0.363 | Hard | 12,162 |
https://leetcode.com/problems/cherry-pickup/discuss/1676191/Python3-or-Top-down-solution-or-DP | class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
#Go down or go right
directions = [(1, 0), (0, 1)]
#Enables cache for our dp
@lru_cache(None)
def dp(row_1, row_2, col_1, col_2):
#if we hit a wall or we go out of the grid
if col_1 >= cols or col_2 >= cols or row_1 >= rows or row_2 >= rows or grid[row_1][col_1] == -1 or grid[row_2][col_2] == -1:
return -inf
#Pick current cherries
result = grid[row_1][col_1]
#Do not double cherries if both paths are the same
if col_1 != col_2 or row_1 != row_2:
result += grid[row_2][col_2]
# If we are at the end of the grid stop
if not (row_1 == rows - 1 and col_1 == cols - 1):
result += max(dp(new_row_1 + row_1, new_row_2 + row_2, new_col_1 + col_1, new_col_2 + col_2)
for new_row_1, new_col_1 in directions
for new_row_2, new_col_2 in directions)
return result
ans = dp(0, 0, 0, 0)
return 0 if ans == -inf else ans | cherry-pickup | Python3 | Top-down solution | DP | Jujusp | 0 | 135 | cherry pickup | 741 | 0.363 | Hard | 12,163 |
https://leetcode.com/problems/network-delay-time/discuss/2036405/Python-Simple-Dijkstra-Beats-~90 | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
adj_list = defaultdict(list)
for x,y,w in times:
adj_list[x].append((w, y))
visited=set()
heap = [(0, k)]
while heap:
travel_time, node = heapq.heappop(heap)
visited.add(node)
if len(visited)==n:
return travel_time
for time, adjacent_node in adj_list[node]:
if adjacent_node not in visited:
heapq.heappush(heap, (travel_time+time, adjacent_node))
return -1 | network-delay-time | Python Simple Dijkstra Beats ~90% | constantine786 | 39 | 2,200 | network delay time | 743 | 0.515 | Medium | 12,164 |
https://leetcode.com/problems/network-delay-time/discuss/1614297/Python-3-or-Different-4-Methods-or-No-Explanation | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
dp = [sys.maxsize] * n
dp[k-1] = 0
graph = collections.defaultdict(list)
for s, e, w in times:
graph[s].append((e, w))
visited = set()
heap = [(0, k)]
while heap:
cur, node = heapq.heappop(heap)
dp[node-1] = cur
if node not in visited:
visited.add(node)
n -= 1
for nei, w in graph[node]:
if dp[nei-1] > cur + w:
dp[nei-1] = cur + w
if nei not in visited:
heapq.heappush(heap, (cur + w, nei))
if not n: return cur
return -1 | network-delay-time | Python 3 | Different 4 Methods | No Explanation | idontknoooo | 6 | 512 | network delay time | 743 | 0.515 | Medium | 12,165 |
https://leetcode.com/problems/network-delay-time/discuss/1614297/Python-3-or-Different-4-Methods-or-No-Explanation | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
dp = [[sys.maxsize] * n for _ in range(n)]
graph = collections.defaultdict(list)
for s, e, w in times:
graph[s].append((e, w))
dp[s-1][e-1] = w
for i in range(n):
dp[i][i] = 0
for kk in range(n):
for i in range(n):
for j in range(n):
if dp[i][kk] != sys.maxsize and dp[kk][j] != sys.maxsize:
dp[i][j] = min(dp[i][j], dp[i][kk] + dp[kk][j])
ans = 0
for j in range(n):
ans = max(ans, dp[k-1][j])
return ans if ans != sys.maxsize else -1 | network-delay-time | Python 3 | Different 4 Methods | No Explanation | idontknoooo | 6 | 512 | network delay time | 743 | 0.515 | Medium | 12,166 |
https://leetcode.com/problems/network-delay-time/discuss/1614297/Python-3-or-Different-4-Methods-or-No-Explanation | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
dp = [sys.maxsize] * n
dp[k-1] = 0
for _ in range(n-1):
for s, e, w in times:
if dp[e-1] > dp[s-1] + w:
dp[e-1] = dp[s-1] + w
ans = 0
for i in range(n):
if i != k-1:
ans = max(ans, dp[i])
return ans if ans != sys.maxsize else -1 | network-delay-time | Python 3 | Different 4 Methods | No Explanation | idontknoooo | 6 | 512 | network delay time | 743 | 0.515 | Medium | 12,167 |
https://leetcode.com/problems/network-delay-time/discuss/1614297/Python-3-or-Different-4-Methods-or-No-Explanation | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
dp = [sys.maxsize] * n
dp[k-1] = 0
graph = collections.defaultdict(list)
for s, e, w in times:
graph[s].append((e, w))
dq = collections.deque([k])
visited = set([k])
while dq:
node = dq.popleft()
cost = dp[node-1]
visited.remove(node)
for nei, w in graph[node]:
if dp[nei-1] > cost + w:
dp[nei-1] = cost + w
if nei not in visited:
visited.add(nei)
dq.append(nei)
ans = 0
for i in range(n):
if i != k-1:
ans = max(ans, dp[i])
return ans if ans != sys.maxsize else -1 | network-delay-time | Python 3 | Different 4 Methods | No Explanation | idontknoooo | 6 | 512 | network delay time | 743 | 0.515 | Medium | 12,168 |
https://leetcode.com/problems/network-delay-time/discuss/2004199/Python3%3A-Dijkstra's-Algorithm-(easy-to-understand) | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
# This problem requires dijkstra's algorithm, where we find the shortest
# distance between a source vertex to all the other vertices.
# If any of the other vertices could not be reached, return -1.
# Else return the largest distance.
# Construct an adjacency list.
# Note: ignore 0th index because there is no node 0.
adjList = [[] for _ in range(n + 1)]
for edge in times:
# edge[0] is src, edge[1] is dest, edge[2] is time taken.
adjList[edge[0]].append([edge[1], edge[2]])
# Initialise the queue and dist array.
queue = {}
dist = [float('inf')] * (n + 1)
# Set the distances of all vertices to be initially inf (not found).
for vertex in range(n):
queue[vertex] = float('inf')
# Set the distance of the source vertex to be 0.
dist[k] = 0
queue[k] = 0
# While queue is not empty.
while (len(queue) > 1):
# Remove the vertex with the smallest edge from the queue.
v = min(queue, key = queue.get)
queue.pop(v)
# If the smallest-distance vertex has a distance of float('inf'),
# then there's no path between source to the rest of the vertices.
if dist[v] == float('inf'): break
# Loop through the neighbours of v.
for w in adjList[v]:
# w[0] is the neighbour vertex, w[1] is the distance between
# v and w.
if (w[0] == k): continue
newDist = dist[v] + w[1]
if (newDist < dist[w[0]]):
dist[w[0]] = newDist
queue[w[0]] = newDist
# If a node is unreachable, return -1.
if float('inf') in dist[1:]: return -1
# Else, return max dist in the list.
return max(dist[1:]) | network-delay-time | Python3: Dijkstra's Algorithm (easy to understand) | anjerraa | 2 | 137 | network delay time | 743 | 0.515 | Medium | 12,169 |
https://leetcode.com/problems/network-delay-time/discuss/2767908/Python-Dijkstra-Algorithm-(-Simple-Soln-with-comments) | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
#create adjacency list
adjList = {i:[] for i in range(1, n+1)} #node: [neighbour, weight]
for src, dest, weight in times:
adjList[src].append([dest, weight])
#create minHeap
minHeap = []
minHeap.append([0, k])
heapq.heapify(minHeap)
#dikjstra
dist = [float("inf")] * (n+1)
dist[k] = 0
while minHeap:
dis, node = heapq.heappop(minHeap)
for it in adjList[node]:
edgeWeight = it[1]
edgeNode = it[0]
if (dis+edgeWeight) < dist[edgeNode]:
dist[edgeNode] = dis+edgeWeight
heapq.heappush(minHeap, [dist[edgeNode], edgeNode])
#result
return max(dist[1:]) if max(dist[1:]) != float("inf") else -1 | network-delay-time | Python - Dijkstra Algorithm ( Simple Soln with comments) | logeshsrinivasans | 1 | 123 | network delay time | 743 | 0.515 | Medium | 12,170 |
https://leetcode.com/problems/network-delay-time/discuss/2176431/Python3-3-solutions-DFS-BFS-Dijkstra | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
## RC ##
## APPROACH 1 : DFS + Visited ##
## Not optimized method, barely passed, always use BFS for shortest path algorithms ##
graph = collections.defaultdict(list)
visited = {}
for u, v, w in times:
graph[u].append((v, w))
visited[u] = float('inf')
visited[v] = float('inf')
if len(visited) != n:
return -1
def dfs(node, weight):
if weight < visited[node]:
visited[node] = weight
for v, w in graph[node]:
dfs(v, weight + w)
# dfs(k, 0)
# if max(visited.values()) == float('inf'):
# return -1
# return max(visited.values())
## APPROACH 2 : BFS ##
queue = collections.deque([(k, 0)])
while(queue):
node, weight = queue.popleft()
if weight < visited[node]:
visited[node] = weight
for v, w in graph[node]:
queue.append((v, weight + w))
if max(visited.values()) == float('inf'):
return -1
return max(visited.values())
## APPROACH 3: Dijkstra Algorithm ##
## Application: Single source shortest path ( weighted ) ##
pq=[(0, k)] # (weight, start-node)
visited = {}
while(pq):
weight, node = heapq.heappop(pq)
if node not in visited:
visited[node] =weight
for v, w in graph[node]:
heapq.heappush(pq, (weight + w, v))
if len(visited) != n:
return -1
return max(visited.values()) | network-delay-time | [Python3] 3 solutions DFS, BFS, Dijkstra | 101leetcode | 1 | 71 | network delay time | 743 | 0.515 | Medium | 12,171 |
https://leetcode.com/problems/network-delay-time/discuss/1590202/Python-Solution-Beats-96.99-Of-python-Solution-(-DIJKSTRA-Algo) | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
distance=[float('inf')]*n
distance[k-1]=0
visited=[False]*n
heap=[(0,k-1)]
adj=defaultdict(list)
for u,v,w in times:adj[u-1].append((v-1,w))
while heap:
mi,u=heapq.heappop(heap)
visited[u]=True
for v,w in adj[u]:
if not visited[v]:
if mi+w<distance[v]:
distance[v]=mi+w
heapq.heappush(heap,(mi+w,v))
ans=max(distance)
#print(distance)
#print(adj)
return ans if ans!=float('inf') else -1 | network-delay-time | Python Solution Beats 96.99% Of python Solution ( DIJKSTRA Algo) | reaper_27 | 1 | 77 | network delay time | 743 | 0.515 | Medium | 12,172 |
https://leetcode.com/problems/network-delay-time/discuss/1214552/Python3-Solution-using-Djikstra-and-heap | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
# implemented using dijkstra's shortest path
graph = {} # create graph
for u, v, w in times:
if u not in graph.keys():
graph[u] = [(v, w)]
else:
graph[u].append((v, w))
min_heap = [(0, k)] # push starting node k into heap, cost is 0
costs = {}
while len(min_heap) != 0:
cost, node = heapq.heappop(min_heap) # pop node with smallest cost
if node in costs.keys(): # check for duplicates
continue
costs[node] = cost
if node not in graph.keys(): # prevent key error
continue
for neighbor, c in graph[node]:
if neighbor not in costs.keys():
heapq.heappush(min_heap, (cost + c, neighbor)) # push all the neighbors into heap (may push duplicate nodes)
if len(costs) == n:
return max(costs.values())
else:
return -1 | network-delay-time | Python3 Solution using Djikstra and heap | JensonC0012 | 1 | 85 | network delay time | 743 | 0.515 | Medium | 12,173 |
https://leetcode.com/problems/network-delay-time/discuss/1137280/Python-or-Dijkstra's-Algorithm-or-Beats-99 | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
graph = {i:dict() for i in range(1, n+1)}
for u,v,w in times:
graph[u][v] = w
dist = [float('inf') for i in range(n+1)]
dist[0], dist[k] = 0, 0
visited = [False]*(n+1)
queue = [(0, k)]
heapify(queue)
while len(queue):
minNode = heappop(queue)[1]
if visited[minNode]: continue
visited[minNode] = True
for node in graph[minNode]:
if not visited[node] and dist[minNode] + graph[minNode][node] < dist[node]:
dist[node] = dist[minNode] + graph[minNode][node]
heappush(queue, (dist[node], node))
ans = max(dist)
return ans if ans != float('inf') else -1 | network-delay-time | Python | Dijkstra's Algorithm | Beats 99% | anuraggupta29 | 1 | 118 | network delay time | 743 | 0.515 | Medium | 12,174 |
https://leetcode.com/problems/network-delay-time/discuss/491792/Python3-Dijkstra's-algo | class Solution:
def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
graph = dict() #digraph in contingency list
for u, v, w in times: graph.setdefault(u, []).append((w, v))
dist = [float("inf")]*N
stack = [(0, K)] #depth-first-search
while stack:
d, n = stack.pop()
if dist[n-1] <= d: continue
dist[n-1] = d
for w, v in sorted(graph.get(n, []), reverse=True): stack.append((d+w, v))
ans = max(dist)
return ans if ans < float("inf") else -1 | network-delay-time | [Python3] Dijkstra's algo | ye15 | 1 | 181 | network delay time | 743 | 0.515 | Medium | 12,175 |
https://leetcode.com/problems/network-delay-time/discuss/491792/Python3-Dijkstra's-algo | class Solution:
def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
"""bellman-ford algorithm"""
dist = [float("inf")]*N
dist[K-1] = 0
for _ in range(N-1):
for u, v, w in times:
dist[v-1] = min(dist[v-1], dist[u-1]+w)
ans = max(dist)
return ans if ans < float("inf") else -1 | network-delay-time | [Python3] Dijkstra's algo | ye15 | 1 | 181 | network delay time | 743 | 0.515 | Medium | 12,176 |
https://leetcode.com/problems/network-delay-time/discuss/491792/Python3-Dijkstra's-algo | class Solution:
def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
"""floyd-warshall algorithm"""
dist = [[float("inf")]*N for _ in range(N)]
for i in range(N): dist[i][i] = 0
for u, v, w in times: dist[u-1][v-1] = w
for k in range(N):
for i in range(N):
for j in range(N):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
ans = max(dist[K-1])
return ans if ans < float("inf") else -1 | network-delay-time | [Python3] Dijkstra's algo | ye15 | 1 | 181 | network delay time | 743 | 0.515 | Medium | 12,177 |
https://leetcode.com/problems/network-delay-time/discuss/2786606/Python-Dijkstra | class Solution:
# main challenge is that it seems like the value of the queue needs to change.
# solved by ignoring any queue item that has been updated.
def networkDelayTime(self, times: List[List[int]], n: int, k: int):
# build adjacency list
graph = [{} for _ in range(n)]
for edge in times:
source, target, delay = edge[0], edge[1], edge[2]
# minus 1 to change from 1 - n to 0 - (n - 1)
graph[source - 1][target - 1] = delay
temp_received_time = [float('inf') for i in range(n)]
# set as start node
temp_received_time[k - 1] = 0
# heap for possible smallest next node
h = []
heapq.heappush(h, (0, k - 1))
while h:
cur_time, cur_node = heapq.heappop(h)
if cur_time > temp_received_time[cur_node]:
# this node has been updated and dealt before(since it has smaller time, which means higher precedence)
continue
for neighbour in graph[cur_node]:
neighbour_time = cur_time + graph[cur_node][neighbour]
if neighbour_time < temp_received_time[neighbour]:
temp_received_time[neighbour] = neighbour_time
heapq.heappush(h, (neighbour_time, neighbour))
# get the max time
max_time = 0
for time in temp_received_time:
if time == float('inf'):
return -1
max_time = max(max_time, time)
return max_time | network-delay-time | [Python] Dijkstra | i-hate-covid | 0 | 4 | network delay time | 743 | 0.515 | Medium | 12,178 |
https://leetcode.com/problems/network-delay-time/discuss/2043011/Python-DjikstraBFS-or-O(E-log-V) | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
edges = collections.defaultdict(list)
for u, v, w in times:
edges[u].append((v, w))
minHeap = [(0, k)]
visited = set()
t = 0
while minHeap:
w1, n1 = heapq.heappop(minHeap)
if n1 in visited:
continue
visited.add(n1)
t = max(t, w1)
for n2, w2 in edges[n1]:
if n2 not in visited:
heapq.heappush(minHeap, (t + w2, n2))
return t if len(visited) == n else -1 | network-delay-time | [Python] Djikstra/BFS | O(E log V) | tejeshreddy111 | 0 | 24 | network delay time | 743 | 0.515 | Medium | 12,179 |
https://leetcode.com/problems/network-delay-time/discuss/2039595/Python-Dijkstra-algorithm | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
adj = defaultdict(list)
for u, v, w in times:
adj[u].append((v, w))
q = [(0, k)]
seen = set()
while q:
if q[0][1] in seen:
heapq.heappop(q)
continue
time, node = heapq.heappop(q)
seen.add(node)
for adj_node, w in adj[node]:
if adj_node not in seen:
heapq.heappush(q, (time + w, adj_node))
return time if len(seen) == n else -1 | network-delay-time | Python, Dijkstra algorithm | blue_sky5 | 0 | 22 | network delay time | 743 | 0.515 | Medium | 12,180 |
https://leetcode.com/problems/network-delay-time/discuss/2038547/Python3-Solution-with-using-dfsbfs | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
g = collections.defaultdict(list)
# build graph
for src, dst, weight in times:
g[src].append((dst, weight))
# k - node, v - weight (src to k)
node2ws = {i: float('inf') for i in range(1, n + 1)}
def dfs(source, cur_weight):
if cur_weight < node2ws[source]:
node2ws[source] = cur_weight
for neigb, w in g[source]:
dfs(neigb, cur_weight + w)
dfs(k, 0)
ws = node2ws.values()
_max = max(ws)
return _max if _max != float('inf') else -1 | network-delay-time | [Python3] Solution with using dfs/bfs | maosipov11 | 0 | 25 | network delay time | 743 | 0.515 | Medium | 12,181 |
https://leetcode.com/problems/network-delay-time/discuss/2038547/Python3-Solution-with-using-dfsbfs | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
g = collections.defaultdict(list)
# build graph
for src, dst, weight in times:
g[src].append((dst, weight))
# k - node, v - weight (src to k)
node2ws = {i: float('inf') for i in range(1, n + 1)}
node2ws[k] = 0
q= collections.deque()
q.append((k, 0))
while q:
cur_node, cur_w = q.popleft()
for neigb, neigb_w in g[cur_node]:
if cur_w + neigb_w < node2ws[neigb]:
node2ws[neigb] = cur_w + neigb_w
q.append((neigb, cur_w + neigb_w))
ws = node2ws.values()
_max = max(ws)
return _max if _max != float('inf') else -1 | network-delay-time | [Python3] Solution with using dfs/bfs | maosipov11 | 0 | 25 | network delay time | 743 | 0.515 | Medium | 12,182 |
https://leetcode.com/problems/network-delay-time/discuss/2036541/python3-shortest-path-algo-%2B-BFS | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
# n = num of nodes, k = source
group = collections.defaultdict(list)
# source: list of [target, time]
for u, v, w in times:
group[u].append([v, w])
node2time = collections.defaultdict(int)
queue = collections.deque([[k, 0]])
ans = 0
node2time[k] = 0
while queue:
cur, total_time = queue.popleft()
if cur in group:
for nxt, time_taken in group[cur]:
t = total_time + time_taken
if nxt in node2time and t >= node2time[nxt]: # shorter path is found already
continue
else:
node2time[nxt] = t
queue.append([nxt, t])
if len(node2time) != n:
return -1
else:
return max(node2time.values()) | network-delay-time | [python3] shortest path algo + BFS | sshinyy | 0 | 15 | network delay time | 743 | 0.515 | Medium | 12,183 |
https://leetcode.com/problems/network-delay-time/discuss/2036352/Simple-Python-Solution-oror-Dijkstra | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
d=defaultdict(list)
for src,dst,t in times:
d[src].append((dst,t))
q=[(0,k)]
visited=set()
max_cost=0
while q:
cost,node=heapq.heappop(q)
if node in visited:
continue
visited.add(node)
max_cost=max(max_cost,cost)
neighbours=d[node]
for neighbour in neighbours:
new_node,new_cost=neighbour
if new_node not in visited:
curr_cost=cost+new_cost
heapq.heappush(q,(curr_cost,new_node))
return max_cost if len(visited)==n else -1 | network-delay-time | Simple Python Solution || Dijkstra | a_dityamishra | 0 | 36 | network delay time | 743 | 0.515 | Medium | 12,184 |
https://leetcode.com/problems/network-delay-time/discuss/2036341/Python-Dijkstra's-Algorithm-oror-O(E.logV)-Time-Complexity-oror-Simple-and-Easy-Solution | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
edges = collections.defaultdict(list)
for u, v, w in times:
edges[u].append((v, w))
t = 0
minHeap = [(0, k)]
visit = set()
while minHeap:
w1, n1 = heapq.heappop(minHeap)
if n1 in visit:
continue
visit.add(n1)
t = max(t, w1)
for n2, w2 in edges[n1]:
if n2 not in visit:
heapq.heappush(minHeap, (w2 + w1, n2))
return t if len(visit) == n else -1 | network-delay-time | Python - Dijkstra's Algorithm || O(E.logV) Time Complexity || Simple and Easy Solution | dayaniravi123 | 0 | 17 | network delay time | 743 | 0.515 | Medium | 12,185 |
https://leetcode.com/problems/network-delay-time/discuss/2036240/Python-Solution-min-heap-defaultdict(dict)-dijkstras-algorithm | class Solution(object):
def networkDelayTime(self, times, n, k):
"""
:type times: List[List[int]]
:type n: int
:type k: int
:rtype: int
"""
dic = defaultdict(dict)
for x, y, t in times:
dic[x][y] = t
heap = [(0, k)]
seen = set()
res = 0
while heap:
time, curr = heapq.heappop(heap)
seen.add(curr)
if len(seen) == n: return time
for other in dic[curr]:
if other not in seen:
heapq.heappush(heap, (dic[curr][other] + time, other))
return -1 | network-delay-time | Python Solution min-heap defaultdict(dict) dijkstras algorithm | Kennyyhhu | 0 | 50 | network delay time | 743 | 0.515 | Medium | 12,186 |
https://leetcode.com/problems/network-delay-time/discuss/2036231/beat-all | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
visited, matrix = [float('inf')] * n, [[float('inf')] * n for _ in range(n)]
for u, v, w in times:
matrix[u-1][v-1] = w
q = [(0, k-1)]
visited[k-1] = 0
while q:
cur_v, cur_n = heapq.heappop(q)
for nei_n, nei_v in enumerate(matrix[cur_n]):
if visited[nei_n] > cur_v + nei_v:
visited[nei_n] = cur_v + nei_v
heapq.heappush(q, (visited[nei_n], nei_n))
ret = max(visited)
return ret if ret != float('inf') else -1 | network-delay-time | beat all | BichengWang | 0 | 24 | network delay time | 743 | 0.515 | Medium | 12,187 |
https://leetcode.com/problems/network-delay-time/discuss/1847181/Python-Dijkstra | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
import heapq
graph = defaultdict(dict)
for i,j,w in times:
graph[i][j] = w
dist = [float("inf")]*(n+1)
dist[k] = 0
que = [(0,k)]
visited = [False]*(n+1)
while que:
d, node = heapq.heappop(que)
if visited[node]:
continue
visited[node] = True
for child in graph[node]:
if graph[node][child] + d < dist[child]:
dist[child] = graph[node][child] + d
heapq.heappush( que, (dist[child],child) )
ret = max(dist[1:])
return ret if ret!=float("inf") else -1 | network-delay-time | [Python] Dijkstra | haydarevren | 0 | 85 | network delay time | 743 | 0.515 | Medium | 12,188 |
https://leetcode.com/problems/network-delay-time/discuss/1490760/Python-Dijkstra's-with-array-and-self-made-heap | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
graph = [[] for _ in range(n)]
self.createGraph(times, graph)
minDist = [float('inf') for _ in range(n)]
minDist[k - 1] = 0
visited = set()
while len(visited) != n:
currDist, currVertex = self.explore(visited, minDist)
if currDist == float('inf'):
break
visited.add(currVertex)
for node in graph[currVertex]:
vertex, cost = node
if vertex in visited:
continue
newCost = cost + currDist
if newCost < minDist[vertex]:
minDist[vertex] = newCost
return -1 if float('inf') in minDist else max(minDist)
def explore(self, visited, minDist):
smallestDist = float('inf')
smallestNode = -1
for i in range(len(minDist)):
if i in visited:
continue
weight = minDist[i]
if weight <= smallestDist:
smallestDist = weight
smallestNode = i
return smallestDist, smallestNode
def createGraph(self, times, graph):
for time in times:
source, dest, cost = time
graph[source - 1].append((dest - 1, cost)) | network-delay-time | Python Dijkstra's with array and self-made heap | SleeplessChallenger | 0 | 142 | network delay time | 743 | 0.515 | Medium | 12,189 |
https://leetcode.com/problems/network-delay-time/discuss/1490760/Python-Dijkstra's-with-array-and-self-made-heap | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
graph = [[] for _ in range(n)]
self.createGraph(graph, times)
minDist = [float('inf') for _ in range(n)]
minDist[k - 1] = 0
min_heap = MinHeap([(idx, float('inf')) for idx in range(n)])
min_heap.update(k - 1, 0)
while not min_heap.check():
vertex, cost = min_heap.remove()
if cost == float('inf'):
break
for i in graph[vertex]:
node, dist = i
newDist = dist + cost
if newDist < minDist[node]:
minDist[node] = newDist
min_heap.update(node, newDist)
return -1 if float('inf') in minDist else max(minDist)
def createGraph(self, graph, times):
for time in times:
source, dest, cost = time
graph[source - 1].append((dest - 1, cost))
class MinHeap:
def __init__(self, arr):
self.vertex = {idx: idx for idx in range(len(arr))}
self.heap = self.buildHeap(arr)
def check(self):
return len(self.heap) == 0
def buildHeap(self, arr):
parentIdx = (len(arr) - 2) // 2
for i in reversed(range(parentIdx + 1)):
self.siftDown(i, len(arr) - 1, arr)
return arr
def remove(self):
if self.check():
return
self.swapValues(0, len(self.heap) - 1, self.heap)
idx, node = self.heap.pop()
del self.vertex[idx]
self.siftDown(0, len(self.heap) - 1, self.heap)
return idx, node
def siftDown(self, idx, length, arr):
idxOne = idx * 2 + 1
while idxOne <= length:
idxTwo = idx * 2 + 2 if idx * 2 + 2 <= length else -1
if idxTwo != -1 and arr[idxOne][1] > arr[idxTwo][1]:
swap = idxTwo
else:
swap = idxOne
if arr[swap][1] < arr[idx][1]:
self.swapValues(swap, idx, arr)
idx = swap
idxOne = idx * 2 + 1
else:
return
def swapValues(self, i, j, arr):
self.vertex[arr[i][0]] = j
self.vertex[arr[j][0]] = i
arr[i], arr[j] = arr[j], arr[i]
def siftUp(self, curr_idx):
parentIdx = (curr_idx - 1) // 2
while curr_idx > 0:
if self.heap[curr_idx][1] < self.heap[parentIdx][1]:
self.swapValues(curr_idx, parentIdx, self.heap)
curr_idx = parentIdx
parentIdx = (curr_idx - 1) // 2
else:
return
def update(self, idx, value):
curr_idx = self.vertex[idx]
self.heap[curr_idx] = (idx, value)
self.siftUp(curr_idx) | network-delay-time | Python Dijkstra's with array and self-made heap | SleeplessChallenger | 0 | 142 | network delay time | 743 | 0.515 | Medium | 12,190 |
https://leetcode.com/problems/network-delay-time/discuss/1174211/python-4-methods%3A-Dijkstra's-Bellman-Ford-bfs-dfs | class Solution(object):
def networkDelayTime(self, times, N, K):
graph = collections.defaultdict(list)
for u, v, w in times:
graph[u].append((w, v))
pq = [(0, K)]
dist = {}
while pq:
d, node = heapq.heappop(pq)
if node in dist: continue
dist[node] = d
for d2, nei in graph[node]:
if nei not in dist:
heapq.heappush(pq, (d+d2, nei))
return max(dist.values()) if len(dist) == N else -1 | network-delay-time | python 4 methods: Dijkstra's, Bellman Ford, bfs, dfs | dustlihy | 0 | 185 | network delay time | 743 | 0.515 | Medium | 12,191 |
https://leetcode.com/problems/network-delay-time/discuss/1174211/python-4-methods%3A-Dijkstra's-Bellman-Ford-bfs-dfs | # class Solution:
# def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
# INF = float('inf')
# dist = [INF] * N
# dist[K-1] = 0
# for i in range(N):
# for time in times:
# 1, time[1] - 1, time[2]
# dist[v] = min(dist[v], dist[u] + w)
# ans = max(dist)
# return ans if ans < INF else -1 | network-delay-time | python 4 methods: Dijkstra's, Bellman Ford, bfs, dfs | dustlihy | 0 | 185 | network delay time | 743 | 0.515 | Medium | 12,192 |
https://leetcode.com/problems/network-delay-time/discuss/1174211/python-4-methods%3A-Dijkstra's-Bellman-Ford-bfs-dfs | # class Solution(object):
# def networkDelayTime(self, times, N, K):
# graph = collections.defaultdict(list)
# for u, v, w in times:
# graph[u].append((w, v)) # u --> v
# INF = float('inf')
# dist = {i: INF for i in range(1, N+1)}
# queue = collections.deque([(K, 0)])
# while queue:
# node, elasped = queue.popleft()
# if elasped < dist[node]:
# dist[node] = elasped
# for time, nei in sorted(graph[node]):
# queue.append((nei, elasped+time))
# ans = max(dist.values())
# return ans if ans < INF else -1 | network-delay-time | python 4 methods: Dijkstra's, Bellman Ford, bfs, dfs | dustlihy | 0 | 185 | network delay time | 743 | 0.515 | Medium | 12,193 |
https://leetcode.com/problems/network-delay-time/discuss/1174211/python-4-methods%3A-Dijkstra's-Bellman-Ford-bfs-dfs | # class Solution(object):
# def networkDelayTime(self, times, N, K):
# graph = collections.defaultdict(list)
# for u, v, w in times:
# graph[u].append((w, v)) # u --> v
# INF = float('inf')
# dist = {node: INF for node in range(1, N+1)}
# def dfs(node, elasped):
# if dist[node] <= elasped: return
# dist[node] = elasped
# for time, nei in sorted(graph[node]):
# dfs(nei, time+elasped)
# dfs(K, 0)
# ans = max(dist.values())
# return ans if ans < INF else -1 | network-delay-time | python 4 methods: Dijkstra's, Bellman Ford, bfs, dfs | dustlihy | 0 | 185 | network delay time | 743 | 0.515 | Medium | 12,194 |
https://leetcode.com/problems/network-delay-time/discuss/625942/Python-Solution-Djikstra's-Algorithm | class Solution:
def extractMin(self,visited,dist):
mind=float("inf")
mini=0
for i in range(len(visited)):
if not visited[i] and dist[i]<mind:
mini=i
mind=dist[i]
return mini
def djikstra(self,visited,dist,K,times):
for i in range(len(visited)):
curr=self.extractMin(visited,dist)
visited[curr]=1
for j in range(len(times)):
if times[j][0]==(curr+1) and dist[curr]+times[j][2]<dist[times[j][1]-1]:
dist[times[j][1]-1]=dist[curr]+times[j][2]
def networkDelayTime(self, times: List[List[int]], n: int, K: int) -> int:
visited=[0]*n
dist=[float("inf")]*n
dist[K-1]=0
self.djikstra(visited,dist,K,times)
ans=max(dist)
if ans==float("inf"):
return -1
return ans | network-delay-time | Python Solution- Djikstra's Algorithm | Ayu-99 | 0 | 80 | network delay time | 743 | 0.515 | Medium | 12,195 |
https://leetcode.com/problems/network-delay-time/discuss/1456874/Python3-solution-using-Dijkstra's-Algorithm | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
d = {}
graph = [[] for _ in range(n)]
for i in times:
d[(i[0]-1,i[1]-1)] = i[2]
graph[i[0]-1].append(i[1]-1)
parent = [-1]*n
cost = [10**9]*n
visited = [False]*n
cost[k-1] = 0
x = 0
while x <= n-1:
m = (-1,10**9)
for i in range(n):
if not visited[i] and m[1] > cost[i]:
m = (i,cost[i])
for i,j in enumerate(graph[m[0]]):
if (m[0],j) in d and cost[j] > cost[m[0]] + d[(m[0],j)]:
cost[j] = cost[m[0]] + d[(m[0],j)]
parent[j] = m[0]
visited[m[0]] = True
x += 1
return -1 if (max(cost)) == 10**9 else max(cost) | network-delay-time | Python3 solution using Dijkstra's Algorithm | EklavyaJoshi | -1 | 38 | network delay time | 743 | 0.515 | Medium | 12,196 |
https://leetcode.com/problems/find-smallest-letter-greater-than-target/discuss/1568523/Python-easy-solution-with-detail-explanation-(modified-binary-search) | class Solution(object):
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
# if the number is out of bound
if target >= letters[-1] or target < letters[0]:
return letters[0]
low = 0
high = len(letters)-1
while low <= high:
mid = (high+low)//2
if target >= letters[mid]: # in binary search this would be only greater than
low = mid+1
if target < letters[mid]:
high = mid-1
return letters[low] | find-smallest-letter-greater-than-target | Python easy solution with detail explanation (modified binary search) | Abeni | 71 | 3,300 | find smallest letter greater than target | 744 | 0.448 | Easy | 12,197 |
https://leetcode.com/problems/find-smallest-letter-greater-than-target/discuss/2507850/4-lines-of-code-easy-understandable-in-Python | class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
t_ord = ord(target) - ord('a')
for i in letters:
l_ord = ord(i) - ord('a')
if l_ord > t_ord:
return i
return letters[0] # if no chrater is gte that target then return 0 index element | find-smallest-letter-greater-than-target | 4 lines of code easy understandable in Python | ankurbhambri | 7 | 79 | find smallest letter greater than target | 744 | 0.448 | Easy | 12,198 |
https://leetcode.com/problems/find-smallest-letter-greater-than-target/discuss/2176655/Python3-solution-O(log-n) | class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
low, high = 0, len(letters) - 1
while low < high:
mid = (low+high) // 2
if letters[mid] <= target:
low = mid + 1
else:
high = mid
return letters[low] if letters[low] > target else letters[0] | find-smallest-letter-greater-than-target | 📌 Python3 solution O(log n) | Dark_wolf_jss | 6 | 154 | find smallest letter greater than target | 744 | 0.448 | Easy | 12,199 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.