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/bulls-and-cows/discuss/515433/Python-The-only-solution-that-sense-to-me
class Solution: def getHint(self, secret: str, guess: str) -> str: A, B, d, n = 0, 0, {}, len(secret) # Create a dictionary to hold all the counts of each digit for l in secret: if l in d: d[l] += 1 else: d[l] = 1 # First loop is going to count the Bulls, so same digits sharing the same position # Also if True decrement the count for respective number for i in range(n): if secret[i] == guess[i]: A += 1 d[secret[i]] -= 1 # Secoud loop is going to count the cows, numbers that are not same is the dictionary # with counts greater than zero # Also decrement the respective number if True for i in range(n): if guess[i] != secret[i] and guess[i] in d and d[guess[i]] > 0: B += 1 d[guess[i]] -= 1 return str(A) + 'A' + str(B) + 'B'
bulls-and-cows
Python - The only solution that sense to me
nuclearoreo
0
188
bulls and cows
299
0.487
Medium
5,300
https://leetcode.com/problems/bulls-and-cows/discuss/422867/Python3-three-lines-(beating-99.94)
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls = sum(s == g for s, g in zip(secret, guess)) cows = sum((Counter(secret) & Counter(guess)).values()) - bulls return f"{bulls}A{cows}B"
bulls-and-cows
Python3 three lines (beating 99.94%)
ye15
0
126
bulls and cows
299
0.487
Medium
5,301
https://leetcode.com/problems/bulls-and-cows/discuss/422867/Python3-three-lines-(beating-99.94)
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls = 0 fqs, fqg = {}, {} #frequency table for s, g in zip(secret, guess): if s == g: bulls += 1 fqs[s] = 1 + fqs.get(s, 0) fqg[g] = 1 + fqg.get(g, 0) cows = sum(min(v, fqg.get(k, 0)) for k, v in fqs.items()) - bulls return f"{bulls}A{cows}B"
bulls-and-cows
Python3 three lines (beating 99.94%)
ye15
0
126
bulls and cows
299
0.487
Medium
5,302
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2395570/Python3-oror-7-lines-binSearch-cheating-wexplanation-oror-TM%3A-9482
class Solution: # Suppose, for example: # nums = [1,8,4,5,3,7], # for which the longest strictly increasing subsequence is arr = [1,4,5,7], # giving len(arr) = 4 as the answer # # Here's the plan: # 1) Initiate arr = [num[0]], which in this example means arr = [1] # # 2) Iterate through nums. 2a) If n in nums is greater than arr[-1], append n to arr. 2b) If # not, determine the furthest position in arr at which n could be placed so that arr # remains strictly increasing, and overwrite the element at that position in arr with n. # 3) Once completed, return the length of arr. # Here's the iteration for the example: # nums = [ _1_, 8,4,5,3,7] arr = [1] (initial step) # nums = [1, _8_, 4,5,3,7] arr = [1, 8] (8 > 1, so append 8) # nums = [1,8, _4_, 5,3,7] arr = [1, 4] (4 < 8, so overwrite 8) # nums = [1_8,4, _5_, 3,7] arr = [1, 4, 5] (5 > 4, so append 5) # nums = [1_8,4,5, _3_, 7] arr = [1, 3, 5] (3 < 5, so overwrite 4) # nums = [1_8,4,5,3, _7_ ] arr = [1, 3, 5, 7] (7 > 5, so append 7) # Notice that arr is not the sequence given above as the correct seq. The ordering for [1,3,5,7] # breaks the "no changing the order" rule. Cheating? Maybe... However len(arr) = 4 is the # correct answer. Overwriting 4 with 3 did not alter the sequence's length. def lengthOfLIS(self, nums: list[int]) -> int: arr = [nums.pop(0)] # <-- 1) initial step for n in nums: # <-- 2) iterate through nums if n > arr[-1]: # <-- 2a) arr.append(n) else: # <-- 2b) arr[bisect_left(arr, n)] = n return len(arr) # <-- 3) return the length of arr
longest-increasing-subsequence
Python3 || 7 lines, binSearch, cheating, w/explanation || T/M: 94%/82%
warrenruud
45
4,100
longest increasing subsequence
300
0.516
Medium
5,303
https://leetcode.com/problems/longest-increasing-subsequence/discuss/1720297/Python-%2B-3-Approaches-%2B-Complexity
# Pure Dynamic Proramming Solution # Time : O(n*(n+1)/2) - O(n^2) # Space: O(n) class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) dp = [0]*n for i in range(n): maX = 0 for j in range(i+1): if nums[j] < nums[i]: if dp[j] > maX: maX = dp[j] dp[i] = maX+1 return max(dp) # Dynamic Programming with Binary Search # Time: O(nlogn), logn for searching the position for the element's and there are n steps. # Space: O(n) from bisect import bisect_left class Solution: def lengthOfLIS(self, nums): dp = [] for elem in nums: idx = bisect_left(dp, elem) if idx == len(dp): dp.append(elem) else: dp[idx] = elem return len(dp) # Dynamic Programming with Binary Search # Time: O(nlogn), logn for searching the position for the element's and there are n steps. # Space: O(1) from bisect import bisect_left class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) for i in range(n): # Here we pass three arg's, which means find the position of nums[i] in the nums array within index i. idx = bisect_left(nums, nums[i], hi=i) if idx != i: nums[idx], nums[i] = nums[i], float(inf) return nums.index(float(inf)) if float(inf) in nums else n
longest-increasing-subsequence
[Python] + 3 Approaches + Complexity ✔
leet_satyam
5
539
longest increasing subsequence
300
0.516
Medium
5,304
https://leetcode.com/problems/longest-increasing-subsequence/discuss/433618/Python-3-O(n-log-n)-Faster-than-99.16-Memory-usage-less-than-100
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: if not nums: return 0 dp = [sys.maxsize] * len(nums) for x in nums: dp[bisect.bisect_left(dp, x)] = x return bisect.bisect(dp, max(nums))
longest-increasing-subsequence
Python 3 - O(n log n) - Faster than 99.16%, Memory usage less than 100%
mmbhatk
3
736
longest increasing subsequence
300
0.516
Medium
5,305
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2215081/Python-or-2-Approaches-or
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: lis = [nums[0]] for num in nums[1:]: if lis and num > lis[-1]: lis.append(num) else: index = bisect_left(lis, num) lis[index] = num return len(lis)
longest-increasing-subsequence
Python | 2 Approaches |
LittleMonster23
2
217
longest increasing subsequence
300
0.516
Medium
5,306
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2215081/Python-or-2-Approaches-or
class Solution: def lengthOfLIS(self, arr: List[int]) -> int: N = len(arr) dp = [1]*N for i in range(1, N): for j in range(i-1, -1, -1): if (1 + dp[j] > dp[i]) and arr[j] < arr[i]: dp[i] = 1 + dp[j] return max(dp)
longest-increasing-subsequence
Python | 2 Approaches |
LittleMonster23
2
217
longest increasing subsequence
300
0.516
Medium
5,307
https://leetcode.com/problems/longest-increasing-subsequence/discuss/1764943/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: @lru_cache(None) def dp(i: int) -> int: # base case if i == 0: return 1 # recurrence relation res = 1 for j in range(i): if nums[i] > nums[j]: res = max(res, 1+dp(j)) return res return max(dp(i) for i in range(len(nums)))
longest-increasing-subsequence
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
2
291
longest increasing subsequence
300
0.516
Medium
5,308
https://leetcode.com/problems/longest-increasing-subsequence/discuss/1764943/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp = [1]*len(nums) res = 1 for i in range(len(nums)): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], 1+dp[j]) res = max(res, dp[i]) return res
longest-increasing-subsequence
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
2
291
longest increasing subsequence
300
0.516
Medium
5,309
https://leetcode.com/problems/longest-increasing-subsequence/discuss/1327441/python-dp-solution
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp = [1] * len(nums) for i in range(1,len(nums)): for j in range(i-1,-1,-1): if nums[j] < nums[i]: dp[i] = max(dp[i],dp[j]+1) return max(dp)
longest-increasing-subsequence
python dp solution
yingziqing123
2
248
longest increasing subsequence
300
0.516
Medium
5,310
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2396249/Python-or-93-faster-or-Two-easy-solution-using-DP-and-Binary-search
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: # ///// O(n^2) //////// dp = [1] * len(nums) for i in range(len(nums)-1,-1,-1): for j in range(i+1,len(nums)): if nums[i] < nums[j]: dp[i] = max(dp[i],1+dp[j]) return max(dp) # /////// O(nlogn) ////// lst = [nums[0]] for i in range(1, len(nums)): cur = nums[i] if lst[-1] < cur: lst.append(cur) continue left = 0 right = len(lst)-1 while left < right: mid = left + (right-left)//2 if cur <= lst[mid]: right = mid else: left = mid+1 lst[right] = cur return len(lst)
longest-increasing-subsequence
Python | 93% faster | Two easy solution using DP and Binary-search
__Asrar
1
90
longest increasing subsequence
300
0.516
Medium
5,311
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2280317/Python-95-Faster-O(nlongn)
class Solution: def lengthOfLIS(self, nums): # using binary search N = len(nums) dp = ['None']*N dp[0] = nums[0] j = 0 for i in range(1,N): if nums[i]>dp[j]: dp[j+1] = nums[i] j+=1 else: # finding the correct index # binary search # upper bound = j # lower bound = 0 l = 0 u = j index = None while l<=u: mid = (l+u)//2 if dp[mid]>=nums[i]: index = mid u = mid-1 elif nums[i]>dp[mid]: l=mid+1 dp[index] = nums[i] count = 0 for i in dp: if i == 'None': break else: count+=1 return count
longest-increasing-subsequence
Python 95% Faster O(nlongn)
Abhi_009
1
233
longest increasing subsequence
300
0.516
Medium
5,312
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2028947/Pythonor-Efficient-Solutionor-Fast
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: LIS = [1] * len(nums) for i in range(len(nums) - 1, -1, -1): for j in range(i + 1, len(nums)): if nums[i] < nums[j]: LIS[i] = max(LIS[i], 1 + LIS[j]) return max(LIS)
longest-increasing-subsequence
Python| Efficient Solution| Fast
shikha_pandey
1
230
longest increasing subsequence
300
0.516
Medium
5,313
https://leetcode.com/problems/longest-increasing-subsequence/discuss/1894481/LC-21Days-ChallengeDay19
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: if len(nums) == 1: return 1 dp = [1] * len(nums) for i in range(1, len(nums)): for j in range(0, i): if nums[j] < nums[i]: dp[i] = max(dp[i], dp[j] + 1) return max(dp)
longest-increasing-subsequence
[LC 21Days Challenge]Day19
hertz2059
1
18
longest increasing subsequence
300
0.516
Medium
5,314
https://leetcode.com/problems/longest-increasing-subsequence/discuss/1676791/Python-maintain-a-increase-stack-and-binary-search.-Time%3A-O(nlogn)-Space%3A-O(n)
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: # Use a stack to store the increasing number # use a binary search to check where the new element should be and replace it # if the num's location is larger then the last index, then append # finally cacluate the len of stack # Time: O(nlogn) Space: O(n) def binary_search(nums,target): l = 0 r = len(nums) while l < r: mid = l +(r-l)//2 if nums[mid] == target: return mid elif nums[mid] < target: l = mid + 1 else: r = mid return l stack = [] for n in nums: i = binary_search(stack,n) if i == len(stack): stack.append(n) else: stack[i] = n return len(stack)
longest-increasing-subsequence
[Python] maintain a increase stack and binary search. Time: O(nlogn) Space: O(n)
JackYeh17
1
285
longest increasing subsequence
300
0.516
Medium
5,315
https://leetcode.com/problems/longest-increasing-subsequence/discuss/557510/Python-Dynamic-programming-solution
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: if len(nums)==0: return 0 lis=[1]*len(nums) for i in range(1,len(nums)): for j in range(0,i): if nums[i]>nums[j]: if lis[i]<=lis[j]: lis[i]=lis[j]+1 return max(lis)
longest-increasing-subsequence
Python Dynamic programming solution
JoyRafatAshraf
1
458
longest increasing subsequence
300
0.516
Medium
5,316
https://leetcode.com/problems/longest-increasing-subsequence/discuss/404995/Easy-Python-DP-with-explanations
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: size = len(nums) if size == 0: return 0 subs = [0]*(size) subs[0] = 1 for i in range(1, size): maximum = 0 for j in range(0, i): if nums[j] < nums[i] and maximum < subs[j]: maximum = subs[j] subs[i] = maximum + 1 return max(subs)
longest-increasing-subsequence
Easy Python DP with explanations
sengoku
1
1,200
longest increasing subsequence
300
0.516
Medium
5,317
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2847301/Python3-and-Java-Dynamic-Programming.-O(n2)-time-complexity
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp = [1] * len(nums) for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: dp[i] = max(dp[i], dp[j]+1) return max(dp)
longest-increasing-subsequence
[Python3 & Java] Dynamic Programming. O(n^2) time complexity
Cceline00
0
1
longest increasing subsequence
300
0.516
Medium
5,318
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2821442/Short-Optimal-time-Solition-The-Best
class Solution: def lengthOfLIS(self, nums: list[int]) -> int: maxkeys = sorted(set(nums)) maxvals = [0] * len(maxkeys) segments = SegmentTree(maxvals, operation=max_operation) for n in nums: index = bisect.bisect_left(maxkeys, n) lead = segments.query(0, index - 1) + 1 if index != 0 else 1 segments.update(index, lead) return segments.query(0, len(maxkeys) - 1)
longest-increasing-subsequence
Short Optimal-time Solition, The Best
Triquetra
0
4
longest increasing subsequence
300
0.516
Medium
5,319
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2804893/Python-or-Easy-to-follow-or-Faster-than-98.71-or-70-ms-or-Dynamic-Programming-or-Memoization
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: memo = [2**31] for n in reversed(nums): for j in range(len(memo) - 1, -1, -1): if n > memo[j]: continue elif n == memo[j]: break elif j == len(memo) - 1: memo.append(n) else: memo[j + 1] = n break return len(memo) - 1
longest-increasing-subsequence
Python | Easy to follow | Faster than 98.71% | 70 ms | Dynamic Programming | Memoization
thomwebb
0
18
longest increasing subsequence
300
0.516
Medium
5,320
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2779283/Python-O(n2)-DP
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) dp = [1] * n for i in range(n): for j in range(i): if nums[i] > nums[j] and dp[i] < dp[j] + 1: dp[i] = dp[j] + 1 return max(dp)
longest-increasing-subsequence
Python, O(n^2), DP
haniyeka
0
7
longest increasing subsequence
300
0.516
Medium
5,321
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2774202/Python-3-or-O(n2)-or-O(n)-or-Dynamic-Programming
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n=len(nums) lis=[1]*n for i in range(1,n): for j in range(i): if nums[j]<nums[i] and lis[i]<=lis[j]: lis[i]=lis[j]+1 return max(lis)
longest-increasing-subsequence
Python 3 | O(n^2) | O(n) | Dynamic Programming
saa_73
0
5
longest increasing subsequence
300
0.516
Medium
5,322
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2766978/python-solution
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp = [1]*len(nums) for i in range(1, len(nums)): for j in range(i): if nums[i]>nums[j]: dp[i] = max(dp[i], dp[j]+1) return max(dp)
longest-increasing-subsequence
python solution
gcheng81
0
7
longest increasing subsequence
300
0.516
Medium
5,323
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2762482/Python3
class Solution: def lengthOfLIS(self, nums) -> int: # tables = [1] # maxs = 1 # for i in range(1,len(nums)): # tables.append(1) # for j in range(0,i): # if nums[j] < nums[i]: # tables[i] = max(tables[i], tables[j]+1) # if tables[i] > maxs: # maxs = tables[i] # return maxs smallests = [] for i in nums: if smallests == None: smallests.append(i) continue left = 0 right = len(smallests)-1 while left <= right: mid = int((left+right)/2) if smallests[mid] > i: right = mid-1 elif smallests[mid] < i: left = mid + 1 else: right = mid-1 if left == len(smallests): smallests.append(0) smallests[left] = i return len(smallests)
longest-increasing-subsequence
Python3
lucy_sea
0
6
longest increasing subsequence
300
0.516
Medium
5,324
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2761311/Python-Dynamic-Programming-Solution
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) # dp[i] - the longest increasing string that ends with nums[i] dp = [1 for _ in range(n)] for i in range(n): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[j]+1, dp[i]) res = max(dp) return res
longest-increasing-subsequence
Python Dynamic Programming Solution
Rui_Liu_Rachel
0
4
longest increasing subsequence
300
0.516
Medium
5,325
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2737604/LIS
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: if not nums: return 0 nlen = len(nums) temp = [] temp.append(nums[0]) for n in range(1,nlen): #print(f'arr:{temp}') if nums[n] in temp:continue position = bisect_right(temp,nums[n]) tlen = len(temp) if position > tlen-1: temp.append(nums[n]) else: temp[position] = nums[n] #print(f'num:{nums[n]},position:{position}') return(len(temp))
longest-increasing-subsequence
LIS
tkrishnakumar30
0
4
longest increasing subsequence
300
0.516
Medium
5,326
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2737528/Python3-Simple-1D-DP
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp = [1] * len(nums) for i in range(len(nums)): for j in range(i): if nums[i] > nums[j]: # cur num > previous num dp[i] = max(dp[i], dp[j]+1) # add prev sum return max(dp)
longest-increasing-subsequence
Python3 Simple 1D DP
jonathanbrophy47
0
10
longest increasing subsequence
300
0.516
Medium
5,327
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2735804/Length-of-Longest-Increasing-Subsequence-(NlogN)-faster-than-96
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: d=[float('inf')]*(len(nums)+1) d.insert(0,-float('inf')) ans=0 for i in nums: k=bisect_left(d,i) if d[k-1]<i<d[k]: d[k]=i ans=max(ans,k) return ans
longest-increasing-subsequence
Length of Longest Increasing Subsequence (NlogN) faster than 96%
ravinuthalavamsikrishna
0
10
longest increasing subsequence
300
0.516
Medium
5,328
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2723528/Python-%2B-detailed-Explanation
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) # dp[i] definition: # the length of longest increasing subsequence in nums[0:i] dp = [1 for x in range(n)] for i in range(n): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j]+1) return max(dp)
longest-increasing-subsequence
Python + detailed Explanation
Michael_Songru
0
20
longest increasing subsequence
300
0.516
Medium
5,329
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2695488/lengthOfLIS
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp = [1] * (len(nums)) for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: dp[i] = max(dp[i], dp[j]+1) return max(dp) # res = [-1] # def backtracking(index,subset): # if index == len(nums): # for i in range(len(subset)-1): # if subset[i] >= subset[i+1]: # return # res[0] = max(res[0],len(subset)) # return # for i in range(index, len(nums)): # subset.append(nums[i]) # backtracking(i+1, subset) # subset.pop() # backtracking(i+1, subset) # backtracking(0, []) # return res[0]
longest-increasing-subsequence
lengthOfLIS
langtianyuyu
0
2
longest increasing subsequence
300
0.516
Medium
5,330
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2686220/Binary-Search-Solution-Python-O(N-LOGN)
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) temp = [] temp.append(nums[0]) for i in range(1, n): if nums[i] > temp[-1]: temp.append(nums[i]) else: ind = bisect.bisect_left(temp, nums[i]) temp[ind] = nums[i] return len(temp)
longest-increasing-subsequence
Binary Search Solution - Python - O(N LOGN)
kritikaparmar
0
11
longest increasing subsequence
300
0.516
Medium
5,331
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2578299/Python-Easy-DP
class Solution: def lengthOfLIS(self, n: List[int]) -> int: lis = [1] * len(n) for i in range(len(n)-1, -1, -1): for j in range(i+1, len(n)): if n[i] < n[j]: lis[i] = max(lis[i], lis[j] + 1) return max(lis)
longest-increasing-subsequence
Python Easy [DP] ✅
Khacker
0
145
longest increasing subsequence
300
0.516
Medium
5,332
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2567510/Python-O(nlogn)
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: def lowerBound(arr, num): lo, hi = 0, len(arr) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if num > arr[mid]: lo = mid + 1 else: hi = mid - 1 return lo ans = [nums[0]] for num in nums: if num > ans[-1]: ans.append(num) else: lb = lowerBound(ans, num) ans[lb] = num return len(ans)
longest-increasing-subsequence
✅ Python O(nlogn)
dhananjay79
0
101
longest increasing subsequence
300
0.516
Medium
5,333
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2549269/Python-DP-Solution
class Solution: def lengthOfLIS(self, nums): n=len(nums) dp=[1]*n # dp[-1]=1 for i in range(n-2,-1,-1): for j in range(i+1,n): if nums[i]<nums[j]: dp[i]=max(dp[j]+1,dp[i]) # else: # dp[i]=max(dp[i],1) # print(dp) return max(dp)
longest-increasing-subsequence
Python - DP Solution
Prithiviraj1927
0
126
longest increasing subsequence
300
0.516
Medium
5,334
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2549206/Python-or-DFS-(Depth-First-Search)
class Solution: def lengthOfLIS(self, nums): n=len(nums) @cache def dfs(i): # print(i) if i==n-1: return 1 a=1 # b=-1 for j in range(i+1,n): if i!=j and nums[j]>nums[i]: # a+=dfs(j) a=max(a,1+dfs(j)) # print(a) return a g=1 for j in range(n): g=max(dfs(j),g) # print(dfs(j)) return g
longest-increasing-subsequence
Python | DFS (Depth First Search)
Prithiviraj1927
0
101
longest increasing subsequence
300
0.516
Medium
5,335
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2548958/Python-or-Recursion-(TLE)
class Solution: def lengthOfLIS(self, nums): n=len(nums) def rec(i,l,prev): # print(i,l,prev) if i==n: return l # p=False # if l>0 and nums[i]>prev: # p=True if nums[i]>prev: return max(rec(i+1,l+1,nums[i]),rec(i+1,l,prev)) else: return rec(i+1,l,prev)
longest-increasing-subsequence
Python | Recursion (TLE)
Prithiviraj1927
0
39
longest increasing subsequence
300
0.516
Medium
5,336
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2539562/Pyhton3-DP-solution
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp=[1]*len(nums) maxx=1 for i in range(1,len(nums)): for j in range(i): if nums[i]>nums[j]: dp[i]=max(dp[i],dp[j]+1) if dp[i]>maxx: maxx=dp[i] return maxx
longest-increasing-subsequence
Pyhton3 DP solution
pranjalmishra334
0
153
longest increasing subsequence
300
0.516
Medium
5,337
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2530444/Dynamic-programming-Time-complexity%3A-O(n)-Space-complexity-O(n)-Python3
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp=[1]*len(nums) #Storing the max length that includes this number using the previous numbers for i in range(1, len(nums)): for j in range(0,i): if nums[j]<nums[i]: dp[i]=max(dp[i],1+dp[j]) #iterating through dp at the end and returning the max return max(dp)
longest-increasing-subsequence
Dynamic programming Time complexity: O(n²) Space complexity O(n) Python3
Simon-Huang-1
0
49
longest increasing subsequence
300
0.516
Medium
5,338
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2436403/python3-greedy-binary-search-O(NlogN)
class Solution: def lengthOfLIS(self, n: List[int]) -> int: res = 0 N = len(n) q = [int(-2e4)] * (N + 1) for i in range(N): l, r = 0, res while l < r: mid = l + r + 1 >> 1 if q[mid] < n[i]: l = mid else: r = mid - 1 q[r + 1] = n[i] res = max(res, r + 1) return res
longest-increasing-subsequence
python3 greedy binary search O(NlogN)
jdai1234
0
84
longest increasing subsequence
300
0.516
Medium
5,339
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2399474/python-solution%3A-200-ms
class Solution: def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ res = [] for num in nums: found = False for i, v in enumerate(res): # now check if we have any greater than number in the list already added, # if yes, then change that number to this new number if num <= v: res[i] = num found = True break if not found: # Add to the list res.append(num) return len(res) s = Solution() nums = [10,9,2,5,3,7,101,18] l = s.lengthOfLIS(nums) print(l)
longest-increasing-subsequence
python solution: 200 ms
user2354hl
0
13
longest increasing subsequence
300
0.516
Medium
5,340
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2398977/Python-Accurate-Solution-oror-Documented
class Solution: # O(n^2) def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) # number of elements dp = [1] * n # every number itself is LIS of 1 for i in range(n-1, -1, -1): # backward loop for j in range(i+1, n): # forward loop from i to end if nums[i] < nums[j]: # element can be included in LIS dp[i] = max(dp[i], dp[j] + 1) # save max count to dp return max(dp) # return max value
longest-increasing-subsequence
[Python] Accurate Solution || Documented
Buntynara
0
11
longest increasing subsequence
300
0.516
Medium
5,341
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2398867/Python-Simple-Python-Solution
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: result = [1] for i in range(1, len(nums)): current_length = 1 for j in range(i): if nums[i] > nums[j]: current_length = max(current_length, 1 + result[j]) result.insert(i, current_length) return max(result)
longest-increasing-subsequence
[ Python ] ✅✅ Simple Python Solution 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
195
longest increasing subsequence
300
0.516
Medium
5,342
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2398106/Sweet-and-Simple-or-Python3
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: LIS = [1] * len(nums) for i in range(len(nums)-1, -1, -1): for j in range(i+1, len(nums)): if nums[i] < nums[j]: LIS[i] = max(LIS[i],1+LIS[j]) return max(LIS)
longest-increasing-subsequence
Sweet and Simple | Python3
25ajeet
0
54
longest increasing subsequence
300
0.516
Medium
5,343
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2396901/Binary-Search-python3-solution-or-O(nlogn)-time
class Solution: # O(nlogn) time, # O(n) space, # Approach: binary search, def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) psedo_LIS = [nums[0]] def binarySearch(lo, hi, target): while True: mid = (lo+hi)//2 num = psedo_LIS[mid] if num == target: return mid elif num < target: if psedo_LIS[mid+1] >= target: return mid+1 lo = mid else: if mid == 0 or psedo_LIS[mid-1] < target: return mid hi = mid-1 for i in range(1, n): num = nums[i] if num > psedo_LIS[-1]: psedo_LIS.append(num) elif num < psedo_LIS[-1]: index = binarySearch(0, len(psedo_LIS)-1, num) psedo_LIS[index] = num return len(psedo_LIS)
longest-increasing-subsequence
Binary Search python3 solution | O(nlogn) time
destifo
0
11
longest increasing subsequence
300
0.516
Medium
5,344
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2396282/GolangPython-2-solutions
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: max_len = 1 dp = [1 for _ in range(len(nums))] for i in range(1,len(nums)): item = nums[i] for j in range(i): prev_item = nums[j] if item > prev_item: if dp[i] < dp[j]+1: dp[i] = dp[j]+1 if dp[i] > max_len: max_len = dp[i] return max_len
longest-increasing-subsequence
Golang/Python 2 solutions
vtalantsev
0
25
longest increasing subsequence
300
0.516
Medium
5,345
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2396282/GolangPython-2-solutions
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: subseq = [] for item in nums: idx = bisect_left(subseq, item) if idx == len(subseq): subseq.append(item) else: subseq[idx] = item return len(subseq)
longest-increasing-subsequence
Golang/Python 2 solutions
vtalantsev
0
25
longest increasing subsequence
300
0.516
Medium
5,346
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2395836/Python-DP-and-Binary-Search-Solutions
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) lis = [1]*n maxLis = 1 for i in range(n): for j in range(i): if nums[i]>nums[j] and lis[i] < lis[j]+1: lis[i] = lis[j]+1 maxLis = max(maxLis,lis[i]) return maxLis
longest-increasing-subsequence
Python DP and Binary Search Solutions
manojkumarmanusai
0
74
longest increasing subsequence
300
0.516
Medium
5,347
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2395836/Python-DP-and-Binary-Search-Solutions
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dummy = [] count = 0 for n in nums: li = bisect.bisect_left(dummy,n) #This performs Binary search if li == len(dummy): dummy.append(n) count+=1 else: dummy[li] = n return count
longest-increasing-subsequence
Python DP and Binary Search Solutions
manojkumarmanusai
0
74
longest increasing subsequence
300
0.516
Medium
5,348
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2337136/Python3-easy-5-Line-Solution
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: LIS = [1] * len(nums) for i in range(len(nums) - 1, - 1, -1): for j in range(i + 1, len(nums)): if nums[i] < nums[j]: LIS[i] = max(LIS[i], 1 + LIS[j]) return max(LIS)
longest-increasing-subsequence
Python3 easy 5 Line Solution
soumyadexter7
0
76
longest increasing subsequence
300
0.516
Medium
5,349
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2310841/DP-oror-Python3-oror-reverse-order
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: # initialize to 1 at all positions res =[1]*len(nums) # for every j # compare with every number behind it for i in reversed(range(len(nums)-1)): for j in range(i+1, len(nums)): if nums[i] < nums[j]: res[i] = max(res[i], res[j]+1) return max(res)
longest-increasing-subsequence
DP || Python3 || reverse order
xmmm0
0
42
longest increasing subsequence
300
0.516
Medium
5,350
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2310051/Simple-clean-DP-solution-in-Python
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: # Init a dp array to store the current length of LIS ending with current index dp = [1]*len(nums) for i in range(len(nums)): for j in range(0, i): # for each i, for each j < i and nums[j] < nums[i], find the max length of dp[i] and dp[j]+1(max LIS ending with j + current element i) if nums[j] < nums[i]: dp[i] = max(dp[i], dp[j]+1) res = 0 # Go through the whole dp array again to find the longest LIS for i in range(len(dp)): res = max(res, dp[i]) return res
longest-increasing-subsequence
Simple clean DP solution in Python
leqinancy
0
28
longest increasing subsequence
300
0.516
Medium
5,351
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2283593/Faster-than-94.11-of-Python3-online-submissions-for-Longest-Increasing-Subsequence.
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: length = len(nums) dp = [None] * length dp[0] = nums[0] size = 0 for i in range(length): if nums[i] > dp[size]: dp[size+1] = nums[i] size += 1 else: l = 0 r = size index = None while l <= r: mid = (l+r) // 2 if dp[mid] >= nums[i]: index = mid r = mid - 1 else: l = mid + 1 dp[index] = nums[i] return size + 1
longest-increasing-subsequence
Faster than 94.11% of Python3 online submissions for Longest Increasing Subsequence.
sagarhasan273
0
189
longest increasing subsequence
300
0.516
Medium
5,352
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2267540/Python-DP-with-full-working-explanation
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: # Time: O(n*n) and Space: O(n) LIS = [1] * len(nums) # in LIS we will store the longest increasing subsequence from that index to the last index for i in range(len(nums) - 1, -1, -1): # staring from the last index, cause LIS[last] = 1 is the base case for j in range(i + 1, len(nums)): # staring from the last+1 index, will run for nums-1 times if nums[i] < nums[j]: # if i < i+1 satisfies the LIS condition LIS[i] = max(LIS[i], 1 + LIS[j]) # then choose the max from i or 1(where 1 indicates i index) + i+1 return max(LIS)
longest-increasing-subsequence
Python DP with full working explanation
DanishKhanbx
0
155
longest increasing subsequence
300
0.516
Medium
5,353
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2226355/Python-solution-using-DP-or-Longest-Increasing-Subsequence
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: length = len(nums) LIS = [1] * length for i in range(length - 1, -1, -1): for j in range(i+1, length): if nums[i] < nums[j]: LIS[i] = max(LIS[i], 1 + LIS[j]) return max(LIS)
longest-increasing-subsequence
Python solution using DP | Longest Increasing Subsequence
nishanrahman1994
0
78
longest increasing subsequence
300
0.516
Medium
5,354
https://leetcode.com/problems/longest-increasing-subsequence/discuss/2204721/Python-easy-to-read-and-understand-or-binary-search
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: lis = [nums[0]] for num in nums[1:]: if lis and num > lis[-1]: lis.append(num) else: index = bisect_left(lis, num) lis[index] = num return len(lis)
longest-increasing-subsequence
Python easy to read and understand | binary-search
sanial2001
0
70
longest increasing subsequence
300
0.516
Medium
5,355
https://leetcode.com/problems/remove-invalid-parentheses/discuss/1555755/Easy-to-understand-Python-solution
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: def valid(s): l,r=0,0 for c in s: if c=='(': l+=1 elif c==')': if l<=0: r+=1 else: l-=1 return not l and not r res=[] seen=set() level={s} while True: newLevel=set() for word in level: if valid(word): res.append(word) if res: return res for word in level: for i in range(len(word)): if word[i] in '()': newWord=word[:i]+word[i+1:] if newWord not in seen: seen.add(newWord) newLevel.add(newWord) level=newLevel return [""]
remove-invalid-parentheses
Easy to understand Python 🐍 solution
InjySarhan
3
375
remove invalid parentheses
301
0.471
Hard
5,356
https://leetcode.com/problems/remove-invalid-parentheses/discuss/1454039/Easy-to-understand-BFS-Python-solution
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: def is_valid(expr): count = 0 for ch in expr: if ch in '()': if ch == '(': count += 1 elif ch == ')': count -= 1 if count < 0: return False return count == 0 queue = collections.deque() queue.append(s) seen = set() seen.add(s) stay_at_this_level = False output = [] while queue: expression = queue.popleft() if is_valid(expression): output.append(expression) stay_at_this_level = True elif not stay_at_this_level: # populate queue with candidiates at the next level i.e. one less ( or ) for i in range(len(expression)): if expression[i] in '()': candidate = expression[:i] + expression[i+1:] if candidate not in seen: queue.append(candidate) seen.add(candidate) return output if output else ['']
remove-invalid-parentheses
Easy to understand BFS Python solution
PK_Leo
2
202
remove invalid parentheses
301
0.471
Hard
5,357
https://leetcode.com/problems/remove-invalid-parentheses/discuss/1249118/Python-DFS-Solution-with-comments
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: #Calculate the number of unmatched left and right redundant_open=0 redundat_close=0 for i in s: if i=="(": redundant_open+=1 elif i==")": if redundant_open>0: redundant_open-=1 else: # If we don't have a matching left, then this is a misplaced right, record it. redundat_close+=1 ans=set() def dfs(index,left,right,ope,close,valid): # If we reached the end of the string, just check if the resulting expression is # valid or not and also if we have removed the total number of left and right # parentheses that we should have removed. if index==len(s): if left==right and ope==0 and close==0: ans.add(valid) return if s[index]=='(': if ope>0: dfs(index+1,left,right,ope-1,close,valid) dfs(index+1,left+1,right,ope,close,valid+"(") elif s[index]==')': if close>0: dfs(index+1,left,right,ope,close-1,valid) if right<left: dfs(index+1,left,right+1,ope,close,valid+")") else: dfs(index+1,left,right,ope,close,valid+s[index]) dfs(0,0,0,redundant_open,redundat_close,"") return list(ans)
remove-invalid-parentheses
Python DFS Solution with comments
jaipoo
2
369
remove invalid parentheses
301
0.471
Hard
5,358
https://leetcode.com/problems/remove-invalid-parentheses/discuss/2807979/backtracking-approach
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: # ((((((((((( # O(2^n), O(n) # backtracking approach self.longest_string = -1 self.res = set() self.dfs(s, 0, [], 0, 0) return self.res def dfs(self, string, cur_idx, cur_res, l_count, r_count): if cur_idx >= len(string): if l_count == r_count: if len(cur_res) > self.longest_string: self.longest_string = len(cur_res) self.res = set() self.res.add("".join(cur_res)) elif len(cur_res) == self.longest_string: self.res.add("".join(cur_res)) else: cur_char = string[cur_idx] if cur_char == "(": cur_res.append(cur_char) # taking cur_char self.dfs(string, cur_idx + 1, cur_res, l_count + 1, r_count) # not taking cur_char cur_res.pop() self.dfs(string, cur_idx + 1, cur_res, l_count, r_count) elif cur_char == ")": self.dfs(string, cur_idx + 1, cur_res, l_count, r_count) # checking of l_count should be greater than r_count if l_count > r_count: cur_res.append(cur_char) # taking ) self.dfs(string, cur_idx + 1, cur_res, l_count, r_count + 1) # not taking ) cur_res.pop() else: # this is for any character except "(" and ")" cur_res.append(cur_char) self.dfs(string, cur_idx + 1, cur_res, l_count, r_count) cur_res.pop()
remove-invalid-parentheses
backtracking approach
sahilkumar158
1
44
remove invalid parentheses
301
0.471
Hard
5,359
https://leetcode.com/problems/remove-invalid-parentheses/discuss/2833563/DFS-Easy-to-Understand-Solution
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: self.minDel = len(s) # 最小刪除數量,預設為字串長度(即可刪除的最大值) self.visited = set() # 已拜訪字串的集合(用來跳過重複搜索的字串),也是不引發 TLE 的關鍵優化 self.ans = set() # 最終答案集合 self.dfs(s, 0) # 若 ans 不為空則將其轉為 list 輸出,若為空則回傳 [""] return list(self.ans) if self.ans else [""] def dfs(self, S, count): # 放棄遞迴條件:字串為空、當前刪除數量 > 全域最小刪除數量、此字串已拜訪過(不需要重複拜訪) if (not S) or (count > self.minDel) or (S in self.visited): return self.visited.add(S) # 將此字串加入已拜訪集合 # 若此字串為合法字串,進行處理並結束此次遞迴 if self.isValid(S): if count < self.minDel : # 若當前刪除數量 < 全域最小刪除數量 self.minDel = count # 則更新全域最小刪除數量 self.ans = {S} # 並重置 ans 集合 elif count == self.minDel: # 若當前刪除數量 == 全域最小刪除數量 self.ans.add(S) # 則將新的字串加入 ans 集合 return for i in range(len(S)): if S[i] in "()": # 若此字元為括號,則將其刪除,並進入下一層遞迴搜尋 self.dfs(S[:i] + S[i+1:], count+1) def isValid(self, S): stack = list() for c in S: if c == "(": stack.append(0) elif c == ")": if stack: # 若有 ( 則消除 stack.pop() else: # 若無 ( 代表字串不合法 return False return stack == [] # 若堆疊為空代表為合法字串,反之不合法
remove-invalid-parentheses
DFS Easy to Understand Solution
child70370636
0
3
remove invalid parentheses
301
0.471
Hard
5,360
https://leetcode.com/problems/remove-invalid-parentheses/discuss/2733520/Python3-BFS-Solution
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: curStack = set([s]) output = set() nextStack = set() if self.valid(s): return [s] while curStack: for node in curStack: for i in range(len(node)): cur = node[:i] + node[i + 1:] if self.valid(cur): output.add(cur) else: nextStack.add(cur) curStack = nextStack nextStack = set() if len(output) > 0: break return list(output) def valid(self, s): leftOpen = 0 for i in range(len(s)): if s[i] == ')': if leftOpen > 0: leftOpen -= 1 else: return False elif s[i] == '(': leftOpen += 1 return leftOpen == 0
remove-invalid-parentheses
Python3 BFS Solution
EricX91
0
13
remove invalid parentheses
301
0.471
Hard
5,361
https://leetcode.com/problems/remove-invalid-parentheses/discuss/2026565/Python-recursive-BFS-solution
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: size = [0] output = set() right_left = s.count(")") dfs(s, output, size, right_left) return output def dfs(s, output, size, right_left, idx=0, left=0, right=0, out=[]): if right > left: return if left-right > right_left: return if idx == len(s): if len(out) < size[-1]: return if left == right: if len(out) > size[-1]: output.clear() size[-1] = len(out) output.add("".join(out)) return item = s[idx] if item == ")": right_left -= 1 dfs(s, output, size, right_left, idx+1, left, right, out) if item == "(": left += 1 elif item == ")": right += 1 out.append(item) dfs(s, output, size, right_left, idx+1, left, right, out) out.pop()
remove-invalid-parentheses
Python recursive BFS solution
vtalantsev
0
123
remove invalid parentheses
301
0.471
Hard
5,362
https://leetcode.com/problems/remove-invalid-parentheses/discuss/1545980/Python-backtracking-solution
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: self.ans = [] self.minMoves = float('inf') @lru_cache(None) def rec(s, count): if not s or count > self.minMoves: return elif self.isValid(s): if count == self.minMoves: self.ans.append(s) else: self.minMoves = count self.ans = [s] for i in range(len(s)): if s[i] in '()': rec(s[:i] + s[i+1:], count+1) rec(s, 0) return self.ans or [''] def isValid(self, s): l, r = 0, 0 for i in range(len(s)): if s[i] == '(': l += 1 elif s[i] == ')': r += 1 if r > l: return False return r == l
remove-invalid-parentheses
Python backtracking solution
SmittyWerbenjagermanjensen
0
270
remove invalid parentheses
301
0.471
Hard
5,363
https://leetcode.com/problems/additive-number/discuss/2764371/Python-solution-with-complete-explanation-and-code
class Solution: def isAdditiveNumber(self, s: str) -> bool: n = len(s) for i in range(1, n): # Choose the length of first number # If length of 1st number is > 1 and starts with 0 -- skip if i != 1 and s[0] == '0': continue for j in range(1, n): # Choose the length of second number # If length of 2nd number is > 1 and starts with 0 -- skip if j != 1 and s[i] == '0': continue # If the total length of 1st and 2nd number >= n -- skip if i + j >= n: break # Just use the brute force approach a = int(s[0: i]) b = int(s[i: i+j]) d = i+j while d < n: c = a + b t = str(c) if s[d: d + len(t)] != t: break d += len(t) a = b b = c if d == n: return True return False
additive-number
Python solution with complete explanation and code
smit5300
0
11
additive number
306
0.309
Medium
5,364
https://leetcode.com/problems/additive-number/discuss/1863442/Python-Simple-Backtrack-with-Explanation
class Solution: def isAdditiveNumber(self, num: str): return self.backtrack(num) def backtrack(self, num: str): path = [] def backtrack(cur_str, cut_size) -> bool: ''' retval means: found ''' # not additive if cut_size >= 3 and path[-1] != path[-2] + path[-3]: return False # end if cur_str == '': return cut_size >= 3 # backtrack for cur_idx in range(1, len(cur_str) + 1): cut_str, remain = cur_str[:cur_idx], cur_str[cur_idx:] # check start 0 if cut_str.startswith('0') and cut_str != '0': break path.append(int(cut_str)) if backtrack(remain, cut_size + 1): return True path.pop() # recover return False return backtrack(num, 0)
additive-number
Python Simple Backtrack with Explanation
steve-jokes
0
249
additive number
306
0.309
Medium
5,365
https://leetcode.com/problems/additive-number/discuss/1761917/Python-3-Recursive-DP
class Solution: def isAdditiveNumber(self, num: str) -> bool: #1 1 1=> 0 1 2 3 #1 1 2=> 0 1 2 4 #1 2 3=> 0 1 3 6 @cache def check(i,j,k,l): if any([i>len(num),j>len(num),k>len(num),l>len(num)]): return False if any([num[i]=="0" and j-i!=1,num[j]=="0" and k-j!=1,num[k]=="0" and l-k!=1]): return False num1=int(num[i:j]) num2=int(num[j:k]) num3=int(num[k:l]) if l==len(num): return num1+num2==num3 o1=max(j-i,k-j) return num1+num2==num3 and (check(j,k,l,l+o1) or check(j,k,l,l+o1+1)) maxPos=len(num)//2 for i in range(1,maxPos+1,1): for j in range(1,maxPos+1,1): o1=max(i,j) if check(0,i,i+j,i+j+o1) or check(0,i,i+j,i+j+o1+1): return True return False
additive-number
Python 3 Recursive DP
ryanzxc34
0
92
additive number
306
0.309
Medium
5,366
https://leetcode.com/problems/additive-number/discuss/1482525/Python-3-or-Iterative-Simulation-or-Explanation
class Solution: def isAdditiveNumber(self, num: str) -> bool: n = len(num) def to_the_end(a, b, i): nonlocal n, num c, c_str = a+b, str(a+b) # sort of do-while loop c_l = len(c_str) while i+c_l <= n and num[i:i+c_l] == c_str: a, b = b, c c, c_str = a+b, str(a+b) i, c_l = i+c_l, len(c_str) return i == n # when index reach to the end for i in range(1, n): # try out all first value possibilities if i > 1 and num[0] == '0': break # leading zero non-zero number, like '02' first = int(num[:i]) for j in range(i+1, n): # try out all second value possibilities if j > i+1 and num[i] == '0': break # leading zero non-zero number, like '02' second = int(num[i:j]) if to_the_end(first, second, j): # given first &amp; second str, see if it can reach to the end return True return False
additive-number
Python 3 | Iterative Simulation | Explanation
idontknoooo
0
276
additive number
306
0.309
Medium
5,367
https://leetcode.com/problems/additive-number/discuss/776765/Python3-enumerate-all-possible-starters
class Solution: def isAdditiveNumber(self, num: str) -> bool: n = len(num) for i in range(1, n//2+1): x = num[:i] if x.startswith("0") and len(x) > 1: break #no leading zero for j in range(i+1, min(n-i, (n+i)//2)+1): #i <= n-j and j-i <= n-j yy = num[i:j] if yy.startswith("0") and len(yy) > 1: break #no leading zero ii, xx = i, x while num.startswith(yy, ii): ii += len(yy) xx, yy = yy, str(int(xx) + int(yy)) if ii == len(num): return True return False
additive-number
[Python3] enumerate all possible starters
ye15
0
97
additive number
306
0.309
Medium
5,368
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2132119/Python-or-Easy-DP-or
class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) dp = [[0 for i in range(2)] for i in range(n+2)] dp[n][0] = dp[n][1] = 0 ind = n-1 while(ind>=0): for buy in range(2): if(buy): profit = max(-prices[ind] + dp[ind+1][0], 0 + dp[ind+1][1]) else: profit = max(prices[ind] + dp[ind+2][1], 0 + dp[ind+1][0]) dp[ind][buy] = profit ind -= 1 return dp[0][1]
best-time-to-buy-and-sell-stock-with-cooldown
Python | Easy DP |
LittleMonster23
4
166
best time to buy and sell stock with cooldown
309
0.546
Medium
5,369
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2132119/Python-or-Easy-DP-or
class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) dp = [[0 for i in range(2)] for i in range(n+2)] dp[n][0] = dp[n][1] = 0 ind = n-1 while(ind>=0): dp[ind][1] = max(-prices[ind] + dp[ind+1][0], 0 + dp[ind+1][1]) dp[ind][0] = max(prices[ind] + dp[ind+2][1], 0 + dp[ind+1][0]) ind -= 1 return dp[0][1]
best-time-to-buy-and-sell-stock-with-cooldown
Python | Easy DP |
LittleMonster23
4
166
best time to buy and sell stock with cooldown
309
0.546
Medium
5,370
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2480511/Python-easy-Solution-or-Best-Approch
class Solution: def f(self,ind,buy,n,price,dp): if ind>=n: return 0 if dp[ind][buy]!=-1: return dp[ind][buy] if (buy==1): dp[ind][buy]=max(-price[ind]+self.f(ind+1,0,n,price,dp),0+self.f(ind+1,1,n,price,dp)) else: #if ind=n-1 so ind+2 will go out of bound base case is if ind>=n: return 0 dp[ind][buy]=max(price[ind]+self.f(ind+2,1,n,price,dp),0+self.f(ind+1,0,n,price,dp)) return dp[ind][buy] def maxProfit(self, prices: List[int]) -> int: n=len(prices) dp=[[-1 for i in range(2)]for j in range(n)] return self.f(0,1,n,prices,dp)
best-time-to-buy-and-sell-stock-with-cooldown
Python easy Solution | Best Approch ✅
adarshg04
3
142
best time to buy and sell stock with cooldown
309
0.546
Medium
5,371
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/762801/Python3-dp
class Solution: def maxProfit(self, prices: List[int]) -> int: buy, sell = inf, 0 for x in prices: buy = min(buy, x) sell = max(sell, x - buy) return sell
best-time-to-buy-and-sell-stock-with-cooldown
[Python3] dp
ye15
3
144
best time to buy and sell stock with cooldown
309
0.546
Medium
5,372
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/762801/Python3-dp
class Solution: def maxProfit(self, prices: List[int]) -> int: buy, sell = inf, 0 for x in prices: buy = min(buy, x - sell) sell = max(sell, x - buy) return sell
best-time-to-buy-and-sell-stock-with-cooldown
[Python3] dp
ye15
3
144
best time to buy and sell stock with cooldown
309
0.546
Medium
5,373
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/762801/Python3-dp
class Solution: def maxProfit(self, prices: List[int]) -> int: buy, sell = [inf]*2, [0]*2 for x in prices: for i in range(2): if i: buy[i] = min(buy[i], x - sell[i-1]) else: buy[i] = min(buy[i], x) sell[i] = max(sell[i], x - buy[i]) return sell[1]
best-time-to-buy-and-sell-stock-with-cooldown
[Python3] dp
ye15
3
144
best time to buy and sell stock with cooldown
309
0.546
Medium
5,374
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/762801/Python3-dp
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: if k >= len(prices)//2: return sum(max(0, prices[i] - prices[i-1]) for i in range(1, len(prices))) buy, sell = [inf]*k, [0]*k for x in prices: for i in range(k): if i: buy[i] = min(buy[i], x - sell[i-1]) else: buy[i] = min(buy[i], x) sell[i] = max(sell[i], x - buy[i]) return sell[-1] if k and prices else 0
best-time-to-buy-and-sell-stock-with-cooldown
[Python3] dp
ye15
3
144
best time to buy and sell stock with cooldown
309
0.546
Medium
5,375
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/762801/Python3-dp
class Solution: def maxProfit(self, prices: List[int]) -> int: buy, cooldown, sell = inf, 0, 0 for x in prices: buy = min(buy, x - cooldown) cooldown = sell sell = max(sell, x - buy) return sell
best-time-to-buy-and-sell-stock-with-cooldown
[Python3] dp
ye15
3
144
best time to buy and sell stock with cooldown
309
0.546
Medium
5,376
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/762801/Python3-dp
class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: buy, sell = inf, 0 for x in prices: buy = min(buy, x - sell) sell = max(sell, x - buy - fee) return sell
best-time-to-buy-and-sell-stock-with-cooldown
[Python3] dp
ye15
3
144
best time to buy and sell stock with cooldown
309
0.546
Medium
5,377
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/1592876/Python-oror-Easy-Solution-oror-Beat~93-oror-O(n)-and-without-extra-space
class Solution: def maxProfit(self, lst: List[int]) -> int: old_buy, old_sell, old_cool = -lst[0], 0, 0 for i in range(1, len(lst)): new_buy, new_sell, new_cool = 0, 0, 0 if (old_cool - lst[i]) > old_buy: new_buy = (old_cool - lst[i]) else: new_buy = old_buy if (lst[i] + old_buy) > old_sell: new_sell = (lst[i] + old_buy) else: new_sell = old_sell if old_cool < old_sell: new_cool = old_sell else: new_cool = old_cool old_buy, old_sell, old_cool = new_buy, new_sell, new_cool return old_sell
best-time-to-buy-and-sell-stock-with-cooldown
Python || Easy Solution || Beat~93% || O(n) and without extra space
naveenrathore
2
179
best time to buy and sell stock with cooldown
309
0.546
Medium
5,378
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/1522708/Python-3-Bottom-up-DP-%2B-memoization-O(n)-time-and-space-code-%2B-comments
class Solution: def maxProfit(self, prices: List[int]) -> int: # Bottom-up dynamic programming with memoization (caching) @lru_cache(None) def dp(day: int, can_buy: True) -> int: # Base case if day >= len(prices): return 0 if can_buy: # We don't own any stocks. Two options: # 1. Don't buy any stocks and go to the next day (wait for a better opportunity) # 2. Buy stocks and go to the next day (with hope to have the best profit) return max(dp(day + 1, True), dp(day + 1, False) - prices[day]) else: # We own stocks. Two options: # 1. Don't sell any stocks and go to the next day (maybe there is a better selling price) # 2. Sell the stocks and go to the day after tomorrow (cooldown tomorrow) return max(dp(day + 1, False), dp(day + 2, True) + prices[day]) # Start with no stocks return dp(0, True)
best-time-to-buy-and-sell-stock-with-cooldown
[Python 3] Bottom-up DP + memoization, O(n) time and space, code + comments
corcoja
2
221
best time to buy and sell stock with cooldown
309
0.546
Medium
5,379
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/1765962/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def maxProfit(self, prices: List[int]) -> int: @lru_cache(None) def dp(i: int, holding: int): # base case if i >= len(prices): return 0 do_nothing = dp(i+1, holding) if holding: # sell stock do_something = prices[i] + dp(i+2, 0) else: # buy stock do_something = -prices[i] + dp(i+1, 1) return max(do_nothing, do_something) return dp(0, 0)
best-time-to-buy-and-sell-stock-with-cooldown
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
1
90
best time to buy and sell stock with cooldown
309
0.546
Medium
5,380
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/1765962/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) dp = [[0]*2 for _ in range(n+1)] for i in range(n-1, -1, -1): for holding in range(2): do_nothing = dp[i+1][holding] if holding: # sell stock do_something = prices[i] + \ dp[i+2][0] if i < n-1 else prices[i] else: # buy stock do_something = -prices[i] + dp[i+1][1] dp[i][holding] = max(do_nothing, do_something) return dp[0][0]
best-time-to-buy-and-sell-stock-with-cooldown
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
1
90
best time to buy and sell stock with cooldown
309
0.546
Medium
5,381
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/1735826/Python-%2B-Easy-Solution
class Solution: def maxProfit(self, prices: List[int]) -> int: obsp = -prices[0] # Old Bought State Profit ossp = 0 # Old Sell State Profit ocsp = 0 # Old Cooldown State Profit for i in range(1, len(prices)): nbsp = 0 # New Bought State Profit nssp = 0 # New Sell State Profit ncsp = 0 # New Cooldown State Profit # Time to Buy... if ocsp-prices[i] > obsp: nbsp = ocsp-prices[i] else: nbsp = obsp # Time to Sell... if obsp+prices[i] > ossp: nssp = obsp+prices[i] else: nssp = ossp # Time to Cooldown... if ossp > ocsp: ncsp = ossp else: ncsp = ocsp obsp = nbsp ossp = nssp ocsp = ncsp return ossp
best-time-to-buy-and-sell-stock-with-cooldown
[Python] + Easy Solution ✔
leet_satyam
1
158
best time to buy and sell stock with cooldown
309
0.546
Medium
5,382
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/1475998/Python3-or-Recursion%2BMemoization
class Solution: def maxProfit(self, prices: List[int]) -> int: self.dp=[[-1 for i in range(2)] for j in range(5001)] return self.dfs(0,0,prices) def dfs(self,day,own,prices): if day>=len(prices): return 0 if self.dp[day][own]!=-1: return self.dp[day][own] if own: p1=prices[day]+self.dfs(day+2,0,prices) p2=self.dfs(day+1,1,prices) else: p1=-prices[day]+self.dfs(day+1,1,prices) p2=self.dfs(day+1,0,prices) self.dp[day][own]=max(p1,p2) return self.dp[day][own]
best-time-to-buy-and-sell-stock-with-cooldown
[Python3] | Recursion+Memoization
swapnilsingh421
1
93
best time to buy and sell stock with cooldown
309
0.546
Medium
5,383
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/764797/Python-solution-with-full-explanation-(theory-%2B-code)
class Solution: def maxProfit(self, prices: List[int]) -> int: cd = 0 sell = 0 buy = float('-inf') for price in prices: old_cd = cd old_sell = sell old_buy = buy cd = max(old_cd, old_sell) sell = old_buy + price buy = max(old_buy, old_cd - price) return max(sell, cd)
best-time-to-buy-and-sell-stock-with-cooldown
Python solution with full explanation (theory + code)
spec_he123
1
94
best time to buy and sell stock with cooldown
309
0.546
Medium
5,384
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2817359/Python-(Simple-DP)
class Solution: def maxProfit(self, prices): @lru_cache(None) def dp(idx,canBuy): if idx >= len(prices): return 0 max_val = dp(idx+1,canBuy) if canBuy: max_val = max(max_val,dp(idx+1,False)-prices[idx]) else: max_val = max(max_val,dp(idx+2,True)+prices[idx]) return max_val return dp(0,True)
best-time-to-buy-and-sell-stock-with-cooldown
Python (Simple DP)
rnotappl
0
5
best time to buy and sell stock with cooldown
309
0.546
Medium
5,385
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2790752/Solution-with-TC-O(n)-and-SC-O(1)-Runtime-95-Faster
class Solution: def maxProfit(self, prices: List[int]) -> int: max_sell = 0 max_buy = 0 prev_buy = 0 for i in range(len(prices)-1,-1,-1): buf_max_sell = max(max_sell,prev_buy+prices[i]) buf_max_buy = max(max_buy,max_sell-prices[i]) max_sell,max_buy,prev_buy = buf_max_sell,buf_max_buy,max_buy return max_buy
best-time-to-buy-and-sell-stock-with-cooldown
Solution with TC O(n) and SC O(1) Runtime 95 % Faster
googlers
0
8
best time to buy and sell stock with cooldown
309
0.546
Medium
5,386
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2779396/Python-Dynamic-Programming-(Top-to-bottom-approach)
class Solution: def maxProfit(self, prices: List[int]) -> int: @cache def dp(i, holding, cooldown): if i == len(prices): return 0 res = dp(i + 1, holding, False) if cooldown: return dp(i + 1, holding, False) if holding: res = max(res, prices[i] + dp(i + 1, False, True)) else: res = max(res, -prices[i] + dp(i + 1, True, False)) return res return dp(0, False, False)
best-time-to-buy-and-sell-stock-with-cooldown
Python Dynamic Programming (Top to bottom approach)
alexdomoryonok
0
6
best time to buy and sell stock with cooldown
309
0.546
Medium
5,387
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2748108/Python3-or-Top-Down-2-D-DP-(Using-Boolean-Flag-State-and-Day-Index-for-Two-State-Parameters)-Approach
class Solution: #Time-Complexity: O(N), since we have 2*N distinct states and 2*N time to intiailize the dp memo! #Space-Complexity: O(N), max stack depth of recursion is N,length of input array prices! Also, memo #takes up 2*N space! def maxProfit(self, prices: List[int]) -> int: #Approach: At every ith day we are on, we want to keep track of whether #we are making decision to buy or sell! However, if we sold stock, we should #skip a day to force cooldown! #I will utilize top-down dp approach with memoization! #Here, I will use two state parameters: day index and boolean flag indicating #buy/sell! n = len(prices) #Dp: I will initialize n arrays, each to store the max profit #we can get from ith day, depending on whether we can buy or sell! dp = [[-1 for _ in range(2)] for _ in range(n)] #define helper function to handle top-down dp! def helper(day, canBuy): nonlocal n, dp #base case: if the day index is out of bounds value, then we return! if(day >= n): return 0 cur_day_price = prices[day] #another base case: if we already solved for current day and mode of #decision, then return answer! if(dp[day][canBuy] != -1): return dp[day][canBuy] #Otherwise, go ahead and solve recursively! #Remember, for current day, we can either buy or not buy! if(canBuy): #recurse for two choices: either buy now or have cooldown! #If we buy now, we consider the rec. call upon day+1th day when we make decision to sell from the day! #However, we need to take account the edge cost of transitioning from our current state to the #rec. call state! buynow = helper(day+1, 0) - cur_day_price #Otherwise, there is no transition regarding profit and we can make same decision btw same set of two #choices again! cooldown1 = helper(day+1, 1) #Make sure to record answer for current state! dp[day][canBuy] = max(buynow, cooldown1) else: #we have two choices again: sell now or cooldown! sellnow = helper(day+2, 1) + cur_day_price cooldown2 = helper(day+1, 0) #Record answer for current state in dp cache here as well! dp[day][canBuy] = max(sellnow, cooldown2) return dp[day][canBuy] #start up the top-down dp recursion and once it terminates, it will return the answer of max profit #when initially making decision to buy or cooldown from day 0! return helper(0, 1)
best-time-to-buy-and-sell-stock-with-cooldown
Python3 | Top-Down 2-D DP (Using Boolean Flag State and Day Index for Two State Parameters) Approach
JOON1234
0
5
best time to buy and sell stock with cooldown
309
0.546
Medium
5,388
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2577675/Naive-recursive-knapsack-python3-solution
class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) @functools.cache def visit(i: int = 0, own: bool = False) -> int: if i >= n: return 0 if not own: return max(-prices[i] + visit(i + 1, True), visit(i + 1, False)) else: return max(prices[i] + visit(i + 2, False), visit(i + 1, True)) return visit()
best-time-to-buy-and-sell-stock-with-cooldown
Naive recursive knapsack python3 solution
jshin47
0
35
best time to buy and sell stock with cooldown
309
0.546
Medium
5,389
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2492544/Interesting-Problem-or-Easy-Solution-or-memo
class Solution: def maxProfit(self, prices: List[int]) -> int: memo = {} def dp(i,state): if i>=len(prices): return 0 elif (i,state) in memo: return memo[(i,state)] else: if state: buy = dp(i+1,not state)-prices[i] cooldown = dp(i+1,state) memo[(i,state)] = max(buy,cooldown) return memo[(i,state)] else: sell = sp(i+2,not state)+prices[i] cooldown = dp(i+1,state) memo[(i,state)] = max(sell,cooldown) return memo[(i,state)] return dp(0,True)
best-time-to-buy-and-sell-stock-with-cooldown
Interesting Problem | Easy Solution | memo
Brillianttyagi
0
47
best time to buy and sell stock with cooldown
309
0.546
Medium
5,390
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2431173/Python-DP-Solution
class Solution: def maxProfit(self, prices: List[int]) -> int: d = {} def bs(index, buyOrNotBuy): if index >= len(prices): return 0 # if we are able to buy the stock, if we already sold it before or # if we have not bought any stock if buyOrNotBuy == "buy": # if buy stock at this index if (index+1, "notBuy") not in d: profit = -1 * prices[index] + bs(index+1, "notBuy") else: profit = -1 * prices[index] + d[(index+1, "notBuy")] # if buy later, not now at this index if (index+1, "buy") not in d: profit1 = bs(index+1, "buy") else: profit1 = d[(index+1, "buy")] d[(index, buyOrNotBuy)] = max(profit, profit1) return d[(index, buyOrNotBuy)] else: # sell stock, if we sell 2nd argument is buy # sell stock at this index if (index+2, "buy") not in d: profit = prices[index] + bs(index+2, "buy") else: profit = prices[index] + d[(index+2, "buy")] # sell stock not at this index now, sell it later if (index+1, "notBuy") not in d: profit1 = bs(index+1, "notBuy") else: profit1 = d[(index+1, "notBuy")] d[(index, buyOrNotBuy)] = max(profit, profit1) return d[(index, buyOrNotBuy)] return bs(0, "buy")
best-time-to-buy-and-sell-stock-with-cooldown
Python DP Solution
DietCoke777
0
27
best time to buy and sell stock with cooldown
309
0.546
Medium
5,391
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2344910/python3-easy-fast
class Solution: def maxProfit(self, prices: List[int]) -> int: dp = {} def dfs(i, buying): if i >= len(prices): return 0 if (i, buying) in dp: return dp[(i, buying)] if buying: buy = dfs(i + 1, not buying) - prices[i] cooldown = dfs(i + 1, buying) dp[(i, buying)] = max(buy, cooldown) else: sell = dfs(i + 2, not buying) + prices[i] cooldown = dfs(i + 1, buying) dp[(i, buying)] = max(sell, cooldown) return dp[(i, buying)] return dfs(0, True)
best-time-to-buy-and-sell-stock-with-cooldown
python3 easy fast
soumyadexter7
0
103
best time to buy and sell stock with cooldown
309
0.546
Medium
5,392
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2318031/Python3-Solution-with-using-state-machine-%2B-dp
class Solution: def maxProfit(self, prices: List[int]) -> int: held, sold, reset = float('-inf'), float('-inf'), 0 for price in prices: held = max(held, reset - price) prev_sold = sold sold = max(sold, held + price) reset = max(reset, prev_sold) return max(reset, sold)
best-time-to-buy-and-sell-stock-with-cooldown
[Python3] Solution with using state machine + dp
maosipov11
0
32
best time to buy and sell stock with cooldown
309
0.546
Medium
5,393
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/1704299/36ms-Two-different-kinds-of-DP%3A-BuySellHold-and-Mathematics
class Solution: def maxProfit(self, prices): return self.dp_opt_v2(prices) def dp(self, prices): # edge if len(prices) == 1: return 0 if len(prices) == 2: return max(0, prices[1] - prices[0]) if len(prices) == 3: return max(0, prices[1] - prices[0], prices[2] - prices[0], prices[2] - prices[1]) # state st_fn = [0] * len(prices) st_gn = [0] * len(prices) # init st_fn[0] = 0 st_fn[1] = max(0, prices[1] - prices[0]) st_fn[2] = max(0, prices[1] - prices[0], prices[2] - prices[0], prices[2] - prices[1]) st_gn[0] = float('-inf') st_gn[1] = max(st_gn[0], -prices[0]) st_gn[2] = max(st_gn[1], -prices[1]) # state transimit equation for n in range(3, len(prices)): st_gn[n] = max(st_gn[n - 1], st_fn[n - 3] - prices[n - 1]) st_fn[n] = max(st_fn[n - 1], prices[n] + st_gn[n]) # ans return st_fn[-1] def dp_opt_v1(self, prices): """ spacial opt, n round only care about previous 3 round """ # edge if len(prices) == 1: return 0 if len(prices) == 2: return max(0, prices[1] - prices[0]) if len(prices) == 3: return max(0, prices[1] - prices[0], prices[2] - prices[0], prices[2] - prices[1]) # state &amp; init st_fn_0 = 0 st_fn_1 = max(0, prices[1] - prices[0]) st_fn_2 = max(0, prices[1] - prices[0], prices[2] - prices[0], prices[2] - prices[1]) st_gn_0 = float('-inf') st_gn_1 = max(st_gn_0, -prices[0]) st_gn_2 = max(st_gn_1, -prices[1]) # state transimit equation for n in range(3, len(prices)): st_gn_0, st_gn_1, st_gn_2 = st_gn_1, st_gn_2, max(st_gn_2, st_fn_0 - prices[n - 1]) st_fn_0, st_fn_1, st_fn_2 = st_fn_1, st_fn_2, max(st_fn_2, prices[n] + st_gn_2) # ans return st_fn_2 def dp_opt_v2(self, prices): """ take advantage of python list spacial opt, n round only care about previous 3 round """ # edge pass # use index -1 -2 # state &amp; init st_fn_0 = 0 st_fn_1 = 0 st_fn_2 = 0 st_gn_2 = float('-inf') # state transimit equation prices += [float('inf'), float('inf')] for n in range(len(prices)): st_gn_2 = max(st_gn_2, st_fn_0 - prices[n - 1]) st_fn_0, st_fn_1, st_fn_2 = st_fn_1, st_fn_2, max(st_fn_2, prices[n] + st_gn_2) # ans return st_fn_0
best-time-to-buy-and-sell-stock-with-cooldown
36ms, Two different kinds of DP: Buy/Sell/Hold and Mathematics
steve-jokes
0
75
best time to buy and sell stock with cooldown
309
0.546
Medium
5,394
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/619314/Python3-very-short-and-simple-DP-O(N)-time-O(1)-space
class Solution: def maxProfit(self, prices: List[int]) -> int: bought, sold, just_sold = -1e18, 0, -1e18 for n in prices: bought, sold, just_sold = max((bought, sold - n)), max((sold, just_sold)), bought + n return max(sold, just_sold)
best-time-to-buy-and-sell-stock-with-cooldown
Python3, very short and simple DP, O(N) time, O(1) space
sugi98765
0
143
best time to buy and sell stock with cooldown
309
0.546
Medium
5,395
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/487086/Python3-short-solution
class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices)<= 1: return 0 temp = [[0],[-prices[0]],[-float("inf")]] for i in range(1,len(prices)): p0,p1,p2=temp[0][-1],temp[1][-1],temp[2][-1] temp[0].append(max(p0,p2)) temp[1].append(max(p1,p0-prices[i])) temp[2].append(p1+prices[i]) return max(temp[0][-1],temp[2][-1])
best-time-to-buy-and-sell-stock-with-cooldown
Python3 short solution
jb07
0
233
best time to buy and sell stock with cooldown
309
0.546
Medium
5,396
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/1782391/Python-easy-to-read-and-understand-or-Step-by-step
class Solution: def solve(self, prices, index, opt): if index >= len(prices): return 0 res = 0 if opt == 0: buy = self.solve(prices, index+1, 1) - prices[index] cool = self.solve(prices, index+1, 0) res = max(buy, cool) else: sell = self.solve(prices, index+2, 0) + prices[index] cool = self.solve(prices, index+1, 1) res = max(sell, cool) return res def maxProfit(self, prices: List[int]) -> int: return self.solve(prices, 0, 0)
best-time-to-buy-and-sell-stock-with-cooldown
Python easy to read and understand | Step by step
sanial2001
-1
103
best time to buy and sell stock with cooldown
309
0.546
Medium
5,397
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/1782391/Python-easy-to-read-and-understand-or-Step-by-step
class Solution: def solve(self, prices, index, opt): if index >= len(prices): return 0 if (index, opt) in self.dp: return self.dp[(index, opt)] if opt == 0: buy = self.solve(prices, index+1, 1) - prices[index] cool = self.solve(prices, index+1, 0) self.dp[(index, opt)] = max(buy, cool) else: sell = self.solve(prices, index+2, 0) + prices[index] cool = self.solve(prices, index+1, 1) self.dp[(index, opt)] = max(sell, cool) return self.dp[(index, opt)] def maxProfit(self, prices: List[int]) -> int: self.dp = {} return self.solve(prices, 0, 0)
best-time-to-buy-and-sell-stock-with-cooldown
Python easy to read and understand | Step by step
sanial2001
-1
103
best time to buy and sell stock with cooldown
309
0.546
Medium
5,398
https://leetcode.com/problems/minimum-height-trees/discuss/1753794/Python-easy-to-read-and-understand-or-reverse-topological-sort
class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: if n == 1: return [0] graph = {i:[] for i in range(n)} for u, v in edges: graph[u].append(v) graph[v].append(u) leaves = [] for node in graph: if len(graph[node]) == 1: leaves.append(node) while len(graph) > 2: new_leaves = [] for leaf in leaves: nei = graph[leaf].pop() del graph[leaf] graph[nei].remove(leaf) if len(graph[nei]) == 1: new_leaves.append(nei) leaves = new_leaves return leaves
minimum-height-trees
Python easy to read and understand | reverse topological sort
sanial2001
7
336
minimum height trees
310
0.385
Medium
5,399