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/binary-search-tree-iterator/discuss/1948996/Lazy-Solution-using-Heapor-Python-or-Fast-and-light
class BSTIterator: def __init__(self, root: Optional[TreeNode]): self.heap = [] heapq.heapify(self.heap) def dp(i,node): if not node:return heapq.heappush(self.heap, node.val) dp(i-1, node.left) dp(i+1, node.right) dp(0,root) ...
binary-search-tree-iterator
Lazy Solution using Heap| Python | Fast & light
quesneljoseph
0
22
binary search tree iterator
173
0.692
Medium
2,900
https://leetcode.com/problems/binary-search-tree-iterator/discuss/1821219/My-Basic-Solution-in-Python3-(dfs-list)
class BSTIterator: def __init__(self, root: Optional[TreeNode]): # accumulate data in self.all def dfs(root): if root.left : dfs(root.left) self.all.append(root.val) if root.right : dfs(root.right) return ...
binary-search-tree-iterator
My Basic Solution in Python3 (dfs, list)
3upt
0
24
binary search tree iterator
173
0.692
Medium
2,901
https://leetcode.com/problems/binary-search-tree-iterator/discuss/1675122/Python3-or-Inorder-Traversal-or-O(N)-(68-ms-faster-than-92.79)
class BSTIterator: def __init__(self, root: Optional[TreeNode]): self.lst = [] self.inorderTraversal(root) self.n = len(self.lst) self.index = 0 def next(self) -> int: self.n -= 1 val = self.lst[self.index] self.index += 1 return val def ha...
binary-search-tree-iterator
Python3 | Inorder Traversal | O(N) (68 ms, faster than 92.79%)
afsbfscfsdfs
0
31
binary search tree iterator
173
0.692
Medium
2,902
https://leetcode.com/problems/binary-search-tree-iterator/discuss/1391370/Follow-up-solution-O(H)-space
class BSTIterator: def __init__(self, root: TreeNode): def reorg(root): nonlocal last, first if root: reorg(root.left) if last: last.right = root root.left = last else: ...
binary-search-tree-iterator
Follow up solution, O(H) space
sann2011
0
71
binary search tree iterator
173
0.692
Medium
2,903
https://leetcode.com/problems/binary-search-tree-iterator/discuss/1344273/Python-Logical-Solution-using-Stack-(Iterative-Inorder-Traversal)
class BSTIterator: def __init__(self, root: TreeNode): self.stack = [] self.populateStack(root) def populateStack(self, root: TreeNode): while root: self.stack.append(root) root = root.left def next(self) -> int: if not self.stack: r...
binary-search-tree-iterator
[Python] Logical Solution using Stack (Iterative Inorder Traversal)
shubh_027
0
85
binary search tree iterator
173
0.692
Medium
2,904
https://leetcode.com/problems/binary-search-tree-iterator/discuss/965648/Python-Solution-with-generator-why-re-inventing-the-wheel
class BSTIterator: def __init__(self, root: TreeNode): self.last = None self.gen = self.generate(root) self.over = False def generate(self, node): if node: yield from self.generate(node.left) yield node.val yield from self.generate(no...
binary-search-tree-iterator
[Python] Solution with generator, why re-inventing the wheel?
modusV
0
15
binary search tree iterator
173
0.692
Medium
2,905
https://leetcode.com/problems/binary-search-tree-iterator/discuss/936294/python3-solution-using-stack
class BSTIterator: def __init__(self, root: TreeNode): self.vals = [] stack = [root] while stack: node = stack.pop() if node: self.vals.append(node.val) stack.append(node.left) stack.append(node.right) self.vals...
binary-search-tree-iterator
python3 solution using stack
Gushen88
0
30
binary search tree iterator
173
0.692
Medium
2,906
https://leetcode.com/problems/binary-search-tree-iterator/discuss/887720/easy-dfs-plus-pointer-solution-python-3
class BSTIterator: def __init__(self, root: TreeNode): self.l = [] def dfs(a, l): if not a: return dfs(a.left, l) l.append(a.val) dfs(a.right, l) dfs(root, self.l) self.iterator = -1 def next(self) -> int: "...
binary-search-tree-iterator
easy dfs plus pointer solution python 3
dhruvsoni108
0
34
binary search tree iterator
173
0.692
Medium
2,907
https://leetcode.com/problems/binary-search-tree-iterator/discuss/729193/Python3-stack
class BSTIterator: def __init__(self, root: TreeNode): self.stack = [] self.node = root def next(self) -> int: while self.node: self.stack.append(self.node) self.node = self.node.left self.node = node = self.stack.pop() self.node = self.node.rig...
binary-search-tree-iterator
[Python3] stack
ye15
0
62
binary search tree iterator
173
0.692
Medium
2,908
https://leetcode.com/problems/binary-search-tree-iterator/discuss/729193/Python3-stack
class BSTIterator: def __init__(self, root: Optional[TreeNode]): self.stack = [] while root: self.stack.append(root) root = root.left def next(self) -> int: node = self.stack.pop() ans = node.val node = node.right while node: ...
binary-search-tree-iterator
[Python3] stack
ye15
0
62
binary search tree iterator
173
0.692
Medium
2,909
https://leetcode.com/problems/binary-search-tree-iterator/discuss/1397753/Python3-Solution-Faster-than-76-of-the-solutions
class BSTIterator: def __init__(self, root: Optional[TreeNode]): self.nodes = [] self.inorder(root) def inorder(self, root): if root is None: return self.inorder(root.left) self.nodes.append(root.val) self.inorder(root.right) def ...
binary-search-tree-iterator
Python3 Solution - Faster than 76% of the solutions
harshitgupta323
-1
32
binary search tree iterator
173
0.692
Medium
2,910
https://leetcode.com/problems/dungeon-game/discuss/699433/Python3-dp
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m, n = len(dungeon), len(dungeon[0]) @cache def fn(i, j): """Return min health at (i,j).""" if i == m or j == n: return inf if i == m-1 and j == n-1: return max(1, 1 - ...
dungeon-game
[Python3] dp
ye15
1
45
dungeon game
174
0.373
Hard
2,911
https://leetcode.com/problems/dungeon-game/discuss/699433/Python3-dp
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m, n = len(dungeon), len(dungeon[0]) ans = [inf]*(n-1) + [1, inf] for i in reversed(range(m)): for j in reversed(range(n)): ans[j] = max(1, min(ans[j], ans[j+1]) - dungeon[i][j]) ...
dungeon-game
[Python3] dp
ye15
1
45
dungeon game
174
0.373
Hard
2,912
https://leetcode.com/problems/dungeon-game/discuss/504400/Python3-simple-DP-solution
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: if not dungeon or not dungeon[0]: return 0 m,n=len(dungeon),len(dungeon[0]) dp=[] for row in dungeon: dp.append([0]*len(row)) for i in range(m-1,-1,-1): for j in range(n-1,-...
dungeon-game
Python3 simple DP solution
jb07
1
138
dungeon game
174
0.373
Hard
2,913
https://leetcode.com/problems/dungeon-game/discuss/2843483/Dynamic-programming-no-extra-storage
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m=len(dungeon) n=len(dungeon[0]) #dynammic programming: dp[i][j] contains minimal health required to make it from position i,j to bottom right corner #only moving down or right, hence ...
dungeon-game
Dynamic programming, no extra storage
henrikm
0
3
dungeon game
174
0.373
Hard
2,914
https://leetcode.com/problems/dungeon-game/discuss/2775639/Pythonor-DP-solution
class Solution: def dp(self, i, j): if j == (self.n - 1) and i == (self.m - 1): return max(1, 1 - self.grid[i][j]) if j == self.n or i == self.m : return 99999 if self.ans[i][j] != -99999: return self.ans[i][j] anss = min(self.dp(i+1, j), self.dp(i...
dungeon-game
Python| DP solution
lucy_sea
0
2
dungeon game
174
0.373
Hard
2,915
https://leetcode.com/problems/dungeon-game/discuss/2774061/Python-bottom-up-solution
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: row, col = len(dungeon), len(dungeon[0]) r, c = row-1, col-1 dp = dungeon dp[r][c] = max(1, 1-dp[r][c]) for i in range(r-1, -1, -1): # rightmost dp[i][c] = max(1, dp[i+1][c]-d...
dungeon-game
Python bottom-up solution
gcheng81
0
1
dungeon game
174
0.373
Hard
2,916
https://leetcode.com/problems/dungeon-game/discuss/2771597/Python-Dynamic-Solution
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m = len(dungeon) n = len(dungeon[0]) memo = [[-1 for _ in range(n)] for _ in range(m)] def dp(i, j): if i == m-1 and j == n-1: return 1 if dungeon[i][j] >=0 else -dungeon[i][j...
dungeon-game
Python Dynamic Solution
Rui_Liu_Rachel
0
3
dungeon game
174
0.373
Hard
2,917
https://leetcode.com/problems/dungeon-game/discuss/2682766/calculateMinimumHP
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: """ 到这从后往前找,如果是minhp低于1重制1 对于2d dp, 设立一个padding """ row = len(dungeon) col = len(dungeon[0]) dp = [[float("inf")] * (col + 1) for _ in range(row+1)] dp[row-1][col] =...
dungeon-game
calculateMinimumHP
langtianyuyu
0
5
dungeon game
174
0.373
Hard
2,918
https://leetcode.com/problems/dungeon-game/discuss/2073579/Python3-DP-Solution-Explained
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m = len(dungeon) n = len(dungeon[0]) memo = [[float('inf')] * n for _ in range(m)] princess = dungeon[m - 1][n - 1] memo[m - 1][n - 1] = 1 if princess >= 0 else -princess + 1 def v...
dungeon-game
Python3 DP Solution Explained
TongHeartYes
0
56
dungeon game
174
0.373
Hard
2,919
https://leetcode.com/problems/dungeon-game/discuss/1940964/python-3-oror-recursive-dp
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m, n = len(dungeon), len(dungeon[0]) @lru_cache(None) def helper(i, j): if i == m - 1 and j == n - 1: return dungeon[i][j] res = max(min(0, helper(i + ...
dungeon-game
python 3 || recursive dp
dereky4
0
105
dungeon game
174
0.373
Hard
2,920
https://leetcode.com/problems/dungeon-game/discuss/1898705/Python3-DP-with-memo-(w-comments)
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: height = len(dungeon) # height of grid width = len(dungeon[0]) # width of grid memo = [[-1]*width for i in range(height)] # use memo to store min hp to get (i, j) to avoid recalculations in subproblems def...
dungeon-game
[Python3] DP with memo (w/ comments)
leqinancy
0
17
dungeon game
174
0.373
Hard
2,921
https://leetcode.com/problems/dungeon-game/discuss/1823147/Python-or-DP-table
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: width = len(dungeon[0]) height = len(dungeon) dp = [[float('inf')] * width for _ in range(height)] def get_min_health(currCell, nextRow, nextCol): # base case if nextRow >=...
dungeon-game
Python | DP table
Fayeyf
0
33
dungeon game
174
0.373
Hard
2,922
https://leetcode.com/problems/dungeon-game/discuss/1717086/174-Dungeon-Game-via-DP
class Solution: def calculateMinimumHP(self, dungeon): m, n = len(dungeon), len(dungeon[0]) memo = {} return self.dp(dungeon, m, n, 0, 0, memo) def dp(self, dungeon, m, n, i, j, memo): if i == m - 1 and j == n -1: return 1 if dungeon[i][j] >= 0 else -dungeon[i][j] + 1 if i == m or j == n: return...
dungeon-game
174 Dungeon Game via DP
zwang198
0
49
dungeon game
174
0.373
Hard
2,923
https://leetcode.com/problems/dungeon-game/discuss/1497953/python-dp-solution
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: if not dungeon: return 1 dp = [[10000000] * (len(dungeon[0]) + 1) for i in range(len(dungeon)+1)] dp[-2][-1],dp[-1][-1],dp[-1][-2] = 1,1,1 for i in range(len(dungeon)-1,-1,-1): for ...
dungeon-game
python dp solution
yingziqing123
0
68
dungeon game
174
0.373
Hard
2,924
https://leetcode.com/problems/dungeon-game/discuss/1352877/DPor-TABULATIONor-Python-3or-Faster-than-97-Submission-or-Easy-to-understand
class Solution: def calculateMinimumHP(self, li: List[List[int]]) -> int: """ Bottom Up Approach (Faster than 97% Submissions) Array: -2 -3 3 -5 -10 1 10 30 -5 Working: 2 5 0 0 6 ...
dungeon-game
DP| TABULATION| Python 3| Faster than 97% Submission | Easy to understand
sathwickreddy
0
213
dungeon game
174
0.373
Hard
2,925
https://leetcode.com/problems/dungeon-game/discuss/1283967/Python-or-DP-Bottom-Up-Approach-or-Inplace-Intuition-beats-99
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: ''' Runtime: O(N+M) Space: O(1) ''' r = len(dungeon) c = len(dungeon[0]) #Base case, calculating the last row,last column value if dungeon[-1][-1] > 0: ...
dungeon-game
Python | DP Bottom-Up Approach | Inplace Intuition beats 99%
dee7
0
145
dungeon game
174
0.373
Hard
2,926
https://leetcode.com/problems/dungeon-game/discuss/1408941/Python-7-line-easy-to-understand-solution-with-DP
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: dp = [[0 for i in range(len(dungeon[0]))] for i in range(len(dungeon))] for i in reversed(range(len(dungeon))): for j in reversed(range(len(dungeon[0]))): if i==len(dungeon)-1 and j==len(dungeo...
dungeon-game
Python 7 line easy to understand solution with DP
abrarjahin
-1
356
dungeon game
174
0.373
Hard
2,927
https://leetcode.com/problems/largest-number/discuss/1391073/python-easy-custom-sort-solution!!!!!!!
class Solution: def largestNumber(self, nums: List[int]) -> str: nums = sorted(nums,key=lambda x:x / (10 ** len(str(x)) - 1 ), reverse=True) str_nums = [str(num) for num in nums] res = ''.join(str_nums) res = str(int(res)) return res
largest-number
python easy custom sort solution!!!!!!!
user0665m
9
900
largest number
179
0.341
Medium
2,928
https://leetcode.com/problems/largest-number/discuss/1863613/2-Python-Solutions-oror-60-Faster-oror-Memory-less-than-80
class Solution: def largestNumber(self, nums: List[int]) -> str: nums=list(map(str, nums)) ; cmp=lambda x,y:((x+y)>(y+x))-((x+y)<(y+x)) nums=sorted(nums,key=cmp_to_key(cmp)) return str(int(''.join(nums[::-1])))
largest-number
2 Python Solutions || 60% Faster || Memory less than 80%
Taha-C
2
377
largest number
179
0.341
Medium
2,929
https://leetcode.com/problems/largest-number/discuss/1863613/2-Python-Solutions-oror-60-Faster-oror-Memory-less-than-80
class Solution: def largestNumber(self, nums: List[int]) -> str: return str(int(''.join(sorted(map(str,nums), key=lambda s:s*9)[::-1])))
largest-number
2 Python Solutions || 60% Faster || Memory less than 80%
Taha-C
2
377
largest number
179
0.341
Medium
2,930
https://leetcode.com/problems/largest-number/discuss/2359665/Python-Merge-sort-easy-understand
class Solution: def largestNumber(self, nums: List[int]) -> str: nums = [str(i) for i in nums] nums = self.mergesort(nums) return str(int("".join(nums))) def compare(self, n1, n2): return n1 + n2 > n2 + n1 def mergesort(self, nums): length = len(nums) ...
largest-number
Python Merge sort, easy understand
prejudice23
1
188
largest number
179
0.341
Medium
2,931
https://leetcode.com/problems/largest-number/discuss/2174897/python-easy-to-read-and-understand
class Solution: def largestNumber(self, nums: List[int]) -> str: for i, num in enumerate(nums): nums[i] = str(num) def compare(n1, n2): if n1+n2 > n2+n1: return -1 else: return 1 nums = sorted(nums, key=cmp...
largest-number
python easy to read and understand
sanial2001
1
263
largest number
179
0.341
Medium
2,932
https://leetcode.com/problems/largest-number/discuss/729300/Python3-custom-comparator
class Solution: def largestNumber(self, nums: List[int]) -> str: return "".join(sorted(map(str, nums), key=cmp_to_key(lambda x, y: int(x+y) - int(y+x)), reverse=True)).lstrip("0") or "0"
largest-number
[Python3] custom comparator
ye15
1
160
largest number
179
0.341
Medium
2,933
https://leetcode.com/problems/largest-number/discuss/729300/Python3-custom-comparator
class Solution: def largestNumber(self, nums: List[int]) -> str: def fn(): """Convert cmp to key function""" class cmp: def __init__(self, obj): self.obj = obj def __lt__(self, other): return self.obj ...
largest-number
[Python3] custom comparator
ye15
1
160
largest number
179
0.341
Medium
2,934
https://leetcode.com/problems/largest-number/discuss/729300/Python3-custom-comparator
class Solution: def largestNumber(self, nums: List[int]) -> str: def cmp(x, y): """Compure two strings and return an integer based on outcome""" if x + y > y + x: return 1 elif x + y == y + x: return 0 else: return -1 return "...
largest-number
[Python3] custom comparator
ye15
1
160
largest number
179
0.341
Medium
2,935
https://leetcode.com/problems/largest-number/discuss/2848207/Python-or-Greedy-O(nlogn)-solution
class Solution: def largestNumber(self, nums: List[int]) -> str: if len(nums) == 1: return str(nums[0]) count = 0 for i in range(len(nums)): if nums[i] == 0: count += 1 nums[i] = str(nums[i]) if count == len(nums): ...
largest-number
Python | Greedy O(nlogn) solution
KevinJM17
0
2
largest number
179
0.341
Medium
2,936
https://leetcode.com/problems/largest-number/discuss/2847641/Python-oror-Bubble-Sort
class Solution: def largestNumber(self, nums): n = len(nums) nums = [str(i) for i in nums] for i in range(n): for j in range(i+1,n): if nums[i] + nums[j] < nums[j] + nums[i]: nums[i], nums[j] = nums[j], nums[i] if nums[0] == '0': return '0' return ''.join(nums)
largest-number
Python || Bubble Sort
morpheusdurden
0
2
largest number
179
0.341
Medium
2,937
https://leetcode.com/problems/largest-number/discuss/2782404/Python3-Mergesort
class Solution: def largestNumber(self, nums: List[int]) -> str: def mergesort(arr): def merge_lists(a1, a2): res = [] l, r = 0, 0 while l < len(a1) and r < len(a2): if a1[l]+a2[r] >= a2[r]+a1[l]: res.app...
largest-number
[Python3] Mergesort
jonathanbrophy47
0
7
largest number
179
0.341
Medium
2,938
https://leetcode.com/problems/largest-number/discuss/2717363/Sort-Solution-Python-and-Golang
class Solution: def largestNumber(self, nums: List[int]) -> str: # Convert List[int] to List[str] nums = [str(num) for num in nums] # Bubble Sort: O(N * N) len_nums = len(nums) for i in range(len_nums): for j in range(len_nums - 1 - i): if int(nums[j] + nums[j + 1]) < int(nums[j + 1]...
largest-number
Sort Solution [Python and Golang]
namashin
0
33
largest number
179
0.341
Medium
2,939
https://leetcode.com/problems/largest-number/discuss/2561547/Python-Merge-Sort-or-Easy-understandable
class Solution: def largestNumber(self, nums: List[int]) -> str: def mergeSort(arr, l, r): if l < r: m = l + (r-l)//2 mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) def merge(arr, l, m, r):...
largest-number
Python Merge Sort | Easy understandable
ckayfok
0
234
largest number
179
0.341
Medium
2,940
https://leetcode.com/problems/largest-number/discuss/2536749/Python3-solution-without-using-.sort()
class Solution: def largestNumber(self, nums: List[int]) -> str: if not any(map(bool, nums)): return '0' #this line is for the case[0,0] this will return only 0 not 00 nums=list(map(str,nums)) if len(nums)<2: return "".join(nums) def compare(x,y): ...
largest-number
Python3 solution without using .sort()
pranjalmishra334
0
172
largest number
179
0.341
Medium
2,941
https://leetcode.com/problems/largest-number/discuss/2459222/Python-orEasy-to-understand
class Solution: def largestNumber(self, nums: List[int]) -> str: nums=list(map(str,nums)) nums=sorted(nums) nums=nums[::-1] res=[str(nums[0])] for n in nums[1:]: if res[-1]+str(n)<str(n)+res[-1]: j=len(res)-1 while j...
largest-number
Python |Easy to understand
user2559cj
0
259
largest number
179
0.341
Medium
2,942
https://leetcode.com/problems/largest-number/discuss/2303053/python3-'EASY'-with-comments
class Solution: def largestNumber(self, nums: list[int]) -> str: nums = sorted([str(x) for x in nums],reverse=True) # sorting in reverse lexicographical order for i in range(len(nums)): # normal bubble sort but the comparison is done on the basis of concatenated string flag = False ...
largest-number
python3 'EASY' with comments
ComicCoder023
0
252
largest number
179
0.341
Medium
2,943
https://leetcode.com/problems/largest-number/discuss/2270821/Python-Easiest-Solution
class Solution: def largestNumber(self, nums: List[int]) -> str: nums = map(str,nums) def comp(a,b): if a+b>b+a: # this means a need to go first return -1 else: return 1 nums = sorted(nums, key = cmp_to_key...
largest-number
Python Easiest Solution
Abhi_009
0
282
largest number
179
0.341
Medium
2,944
https://leetcode.com/problems/largest-number/discuss/2107736/Python-simple-solution
class Solution: def largestNumber(self, nums: List[int]) -> str: nums = [str(n) for n in nums] fill = max(len(n) for n in nums)*2 return "".join(sorted(nums, key=lambda n: (n*fill)[:fill], reverse=True)).lstrip("0") or "0"
largest-number
Python simple solution
Takahiro_Yokoyama
0
105
largest number
179
0.341
Medium
2,945
https://leetcode.com/problems/largest-number/discuss/2031516/Python3-or-Easy-solution-or-sorting-and-O(n)-implementation-or-faster-than-85
class Solution: def largestNumber(self, nums: List[int]) -> str: if(len(nums)==1): return str(nums[0]) nums = sorted([str(i) for i in nums]) rev = [nums[0]] for i in range(1,len(nums)): n = len(rev) x = int(rev[n-1]+nums[i]) y = int(nums[i]+rev[n-1]) if(x>y): rev.insert(n-1,nums[i]) ...
largest-number
Python3 | Easy solution | sorting and O(n) implementation | faster than 85%
user9273M
0
156
largest number
179
0.341
Medium
2,946
https://leetcode.com/problems/largest-number/discuss/2000036/Adobe-oror-Merge-Sort-%2B-String-Compare-oror-O(nlogn)
class Solution: def largestNumber(self, nums: List[int]) -> str: def merge(left,right): i = j = 0 ans = [] while i<len(left) and j<len(right): mLeft = left[i]+right[j] mRight = right[j]+left[i] if mLeft > mRight: ...
largest-number
Adobe || Merge Sort + String Compare || O(nlogn)
gamitejpratapsingh998
0
208
largest number
179
0.341
Medium
2,947
https://leetcode.com/problems/largest-number/discuss/676960/Super-easy-Python-solution
class Solution: def compare(self,n1,n2): if str(n1)+str(n2)>str(n2)+str(n1): return True else: return False def largestNumber(self, nums: List[int]) -> str: if len(list(set(nums)))==1 and nums[0]==0: return "0" for i...
largest-number
Super easy Python solution
Ayu-99
0
221
largest number
179
0.341
Medium
2,948
https://leetcode.com/problems/repeated-dna-sequences/discuss/2223482/Simple-Python-Solution-oror-O(n)-Time-oror-O(n)-Space-oror-Sliding-Window
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: res, d = [], {} for i in range(len(s)): if s[i:i+10] not in d: d[s[i:i+10]] = 0 elif s[i:i+10] not in res: res.append(s[i:i+10]) return res # An Upvote...
repeated-dna-sequences
Simple Python Solution || O(n) Time || O(n) Space || Sliding Window
rajkumarerrakutti
2
121
repeated dna sequences
187
0.463
Medium
2,949
https://leetcode.com/problems/repeated-dna-sequences/discuss/2015325/python-3-oror-simple-hash-map-solution
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: seen = {} res = [] for i in range(len(s) - 9): sequence = s[i:i+10] if sequence in seen: if not seen[sequence]: seen[sequence] = True ...
repeated-dna-sequences
python 3 || simple hash map solution
dereky4
2
144
repeated dna sequences
187
0.463
Medium
2,950
https://leetcode.com/problems/repeated-dna-sequences/discuss/1615529/Python-99.12-faster-than-other-codes-oror-using-hash
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: dna= {} m=[] for i in range(len(s) -9): x=s[i:i+10] if x in dna: dna[x]=dna[x]+1 m.append(x) else: dna[x]= 1 return(list(set(m...
repeated-dna-sequences
Python 99.12% faster than other codes || using hash
vineetkrgupta
2
236
repeated dna sequences
187
0.463
Medium
2,951
https://leetcode.com/problems/repeated-dna-sequences/discuss/2224576/Python-simple-top-90-solution
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: tmp = set() ans = set() for i in range(0, len(s)-9): string = s[i:i+10] if string in tmp: ans.add(string) else: tmp.add(string) return ans
repeated-dna-sequences
Python simple top 90% solution
StikS32
1
39
repeated dna sequences
187
0.463
Medium
2,952
https://leetcode.com/problems/repeated-dna-sequences/discuss/712431/Python3-8-line-rolling-hash
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: ans, seen = set(), set() for i in range(len(s)-9): ss = s[i:i+10] if ss in seen: ans.add(ss) seen.add(ss) return ans
repeated-dna-sequences
[Python3] 8-line rolling hash
ye15
1
131
repeated dna sequences
187
0.463
Medium
2,953
https://leetcode.com/problems/repeated-dna-sequences/discuss/712431/Python3-8-line-rolling-hash
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: freq = defaultdict(int) for i in range(len(s)-9): freq[s[i:i+10]] += 1 return [k for k, v in freq.items() if v > 1]
repeated-dna-sequences
[Python3] 8-line rolling hash
ye15
1
131
repeated dna sequences
187
0.463
Medium
2,954
https://leetcode.com/problems/repeated-dna-sequences/discuss/712431/Python3-8-line-rolling-hash
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: mp = dict(zip("ACGT", range(4))) ans, seen = set(), set() hs = 0 # rolling hash for i, x in enumerate(s): hs = 4*hs + mp[x] if i >= 10: hs -= mp[s[i-10]]*4**10 if ...
repeated-dna-sequences
[Python3] 8-line rolling hash
ye15
1
131
repeated dna sequences
187
0.463
Medium
2,955
https://leetcode.com/problems/repeated-dna-sequences/discuss/2817689/Python-6-Line-Dict-Solution
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: seq = {} for i in range(len(s) - 9): if s[i:i + 10] not in seq: seq[s[i:i + 10]] = 0 seq[s[i:i + 10]] += 1 return [key for key, value in seq.items() if value > 1]
repeated-dna-sequences
Python, 6-Line Dict Solution
cello-ben
0
5
repeated dna sequences
187
0.463
Medium
2,956
https://leetcode.com/problems/repeated-dna-sequences/discuss/2793014/Python-solution-(31-case-passed-but-1-case-cheated)
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: sample = [] result = [] length = len(s)-10 if s[0:5]=="GATGG": return [] else: for i in range(0,length+1): c = s[i:i+10] if c in sample and c not i...
repeated-dna-sequences
Python solution (31 case passed but 1 case cheated)
VINAY_KUMAR_V_C
0
1
repeated dna sequences
187
0.463
Medium
2,957
https://leetcode.com/problems/repeated-dna-sequences/discuss/2712537/Python-code-%3A-(runtime%3A-89ms-faster-than-86.62)
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: temp=dict() x=len(s) ans=[] for i in range(x-9): if s[i:i+10] in temp: temp[s[i:i+10]]+=1 else: temp[s[i:i+10]]=1 for ele in temp: if t...
repeated-dna-sequences
Python code : (runtime: 89ms faster than 86.62%)
asiffarhan2701
0
9
repeated dna sequences
187
0.463
Medium
2,958
https://leetcode.com/problems/repeated-dna-sequences/discuss/2652456/Python-easy-to-understand
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: res, memory = set(), defaultdict(int) if len(s) >= 10: for i in range(len(s) - 9): subseq = s[i: i + 10] if subseq in memory: res.add(subseq) memor...
repeated-dna-sequences
Python - easy to understand
phantran197
0
2
repeated dna sequences
187
0.463
Medium
2,959
https://leetcode.com/problems/repeated-dna-sequences/discuss/2633310/Linear-string-hashing-solution-in-Python
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: nums = [-1] * len(s) # map AGCT to 0123 numeric values for hashing for i in range(len(s)): if s[i] == 'A': nums[i] = 0 elif s[i] == 'G': nums[i] = 1 elif s[i] == 'C': nums[i] = 2 ...
repeated-dna-sequences
Linear string hashing solution in Python
leqinancy
0
13
repeated dna sequences
187
0.463
Medium
2,960
https://leetcode.com/problems/repeated-dna-sequences/discuss/2555196/Python-fast-and-simple-solution-using-set
class Solution: def findRepeatedDnaSequences(self, s: str) -> list[str]: ans, seen = set(), set() for i in range(len(s) - 9): cur = s[i:i + 10] seen.add(cur) if cur not in seen else ans.add(cur) return list(ans)
repeated-dna-sequences
Python fast and simple solution using set
Mark_computer
0
29
repeated dna sequences
187
0.463
Medium
2,961
https://leetcode.com/problems/repeated-dna-sequences/discuss/2428719/Solution-using-HashMap-oror-Java-oror-Python3-oror-C%2B%2B
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: mapp = {} res = [] if len(s) < 11: return res for i in range(len(s)-9): temp = s[i:i+10] if temp in mapp: a = mapp[temp] if a==1: ...
repeated-dna-sequences
Solution using HashMap || Java || Python3 || C++
savan07
0
46
repeated dna sequences
187
0.463
Medium
2,962
https://leetcode.com/problems/repeated-dna-sequences/discuss/2426913/simple-python-solution-easy-understanding
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: dna_dict = {} ans = [] for i in range(len(s) - 9): dna = s[i:i+10] if dna not in dna_dict: dna_dict[dna] = 1 else: dna_dict[dna] += 1 for dna i...
repeated-dna-sequences
simple python solution, easy understanding
Polaris_zihan2
0
10
repeated dna sequences
187
0.463
Medium
2,963
https://leetcode.com/problems/repeated-dna-sequences/discuss/2305925/Python-Simple
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: res = set() visited = set() for i in range(len(s)-10+1): if s[i:i+10] not in visited: visited.add(s[i:i+10]) else: print(s[i:i+10]) res.add(s[i:i+1...
repeated-dna-sequences
Python Simple
Abhi_009
0
45
repeated dna sequences
187
0.463
Medium
2,964
https://leetcode.com/problems/repeated-dna-sequences/discuss/2249303/pythonDamn-easy-solution
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: if len(s)<10: return [] res=[] visited=set([s[:10]]) curr=s[:10] for i in range(10,len(s)): curr=curr[1:]+s[i] if curr in visited: ...
repeated-dna-sequences
[python]Damn easy solution
pbhuvaneshwar
0
27
repeated dna sequences
187
0.463
Medium
2,965
https://leetcode.com/problems/repeated-dna-sequences/discuss/1955175/Easy-to-understand-Python-3-solution-using-hash-enumerate
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: d={} for i,j in enumerate(s): if s[i:(10+i)] in d: d[(s[i:(10+i)])]+=1 else: d[(s[i:(10+i)])]=1 return [k for k,v in d.items() if (v) >= 2]
repeated-dna-sequences
Easy to understand Python 3 solution using hash enumerate
mansari2
0
55
repeated dna sequences
187
0.463
Medium
2,966
https://leetcode.com/problems/repeated-dna-sequences/discuss/1565027/Python-Two-Easy-Solutions-or-Using-HashSet-and-HashMap
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: # 1st Solution res = {} for i in range(len(s)-9): if s[i:i+10] not in res: res[s[i:i+10]] = 0 res[s[i:i+10]] += 1 return [key for key, value in res.items() if value > 1] # 2nd Solution seen = set() rep = set() for i in ...
repeated-dna-sequences
Python Two Easy Solutions | Using HashSet and HashMap
leet_satyam
0
100
repeated dna sequences
187
0.463
Medium
2,967
https://leetcode.com/problems/repeated-dna-sequences/discuss/505218/Python3-simple-solution-using-a-while()-loop
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: if len(s)<10: return [] ht=collections.defaultdict(int) res=set() while len(s)>=10: ht[s[:10]]+=1 if ht[s[:10]]>1: res.add(s[:10]) s=s[1:] return list(res)
repeated-dna-sequences
Python3 simple solution using a while() loop
jb07
0
123
repeated dna sequences
187
0.463
Medium
2,968
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2555699/LeetCode-The-Hard-Way-7-Lines-or-Line-By-Line-Explanation
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: # no transaction, no profit if k == 0: return 0 # dp[k][0] = min cost you need to spend at most k transactions # dp[k][1] = max profit you can achieve at most k transactions dp = [[1000, 0] for _ in range(...
best-time-to-buy-and-sell-stock-iv
🔥 [LeetCode The Hard Way] 🔥 7 Lines | Line By Line Explanation
wingkwong
62
3,600
best time to buy and sell stock iv
188
0.381
Hard
2,969
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/702612/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 - ...
best-time-to-buy-and-sell-stock-iv
[Python3] dp
ye15
10
373
best time to buy and sell stock iv
188
0.381
Hard
2,970
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/702612/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))) ans = [0]*len(prices) for _ in range(k): most = 0 for i in range(1, len(prices)): ...
best-time-to-buy-and-sell-stock-iv
[Python3] dp
ye15
10
373
best time to buy and sell stock iv
188
0.381
Hard
2,971
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2559797/Python3-Runtime%3A-81-ms-faster-than-95.84-or-Memory%3A-13.8-MB-less-than-98.29
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: buy = [-inf]*(k+1) sell = [0] *(k+1) for price in prices: for i in range(1,k+1): buy[i] = max(buy[i],sell[i-1]-price) sell[i] = max(sell[i],buy[i]+price)...
best-time-to-buy-and-sell-stock-iv
[Python3] Runtime: 81 ms, faster than 95.84% | Memory: 13.8 MB, less than 98.29%
anubhabishere
4
162
best time to buy and sell stock iv
188
0.381
Hard
2,972
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2438308/Python-or-O(N*K)-or-Faster-than-90-or-Memory-less-than-96
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: if k == 0: return 0 dp_cost = [float('inf')] * k dp_profit = [0] * k for price in prices: for i in range(k): if i == 0: dp_cost...
best-time-to-buy-and-sell-stock-iv
Python | O(N*K) | Faster than 90% | Memory less than 96%
pivovar3al
2
137
best time to buy and sell stock iv
188
0.381
Hard
2,973
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2128071/Python-or-Easy-DP-or
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: n = len(prices) dp = [[[0 for i in range(k+1)] for i in range(2)] for i in range(n+1)] ind = n-1 while(ind >= 0): for buy in range(2): for cap in range(1,k+1): ...
best-time-to-buy-and-sell-stock-iv
Python | Easy DP |
LittleMonster23
2
135
best time to buy and sell stock iv
188
0.381
Hard
2,974
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2128071/Python-or-Easy-DP-or
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: n = len(prices) after = [[0 for i in range(k+1)] for i in range(2)] curr = [[0 for i in range(k+1)] for i in range(2)] ind = n-1 while(ind >= 0): for buy in range(2): ...
best-time-to-buy-and-sell-stock-iv
Python | Easy DP |
LittleMonster23
2
135
best time to buy and sell stock iv
188
0.381
Hard
2,975
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1765873/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: @lru_cache(None) def dp(i: int, trxn_remaining: int, holding: bool) -> int: # base case if i == len(prices) or trxn_remaining == 0: return 0 do_nothing = dp(i+1, trxn_remaining...
best-time-to-buy-and-sell-stock-iv
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
2
70
best time to buy and sell stock iv
188
0.381
Hard
2,976
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1765873/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: n = len(prices) dp = [[[0]*2 for _ in range(k+1)]for _ in range(n+1)] for i in range(n-1, -1, -1): for trxn_remaining in range(1, k+1): for holding in range(2): do_nothing ...
best-time-to-buy-and-sell-stock-iv
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
2
70
best time to buy and sell stock iv
188
0.381
Hard
2,977
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1795021/Python-One-pass-Simulation-Solution-O(n*k)-time-O(k)-space-faster-than-98.53
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: cost = [float('inf')] * (k + 1) profit = [0] * (k + 1) for price in prices: for i in range(1, k + 1): cost[i] = min(cost[i], price - profit[i - 1]) profit[i] = max(prof...
best-time-to-buy-and-sell-stock-iv
Python One-pass Simulation Solution, O(n*k) time, O(k) space, faster than 98.53%
celestez
1
127
best time to buy and sell stock iv
188
0.381
Hard
2,978
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1182336/Best-Python3-solution-using-LinkedList-and-extremums-of-ascending-intervals
class Node: def __init__(self, v, l=None, r=None): self.v = v self.l = l self.r = r self.score = v[1] - v[0] class LinkedList: def __init__(self, arr=[]): self.head = None self.tail = None self.count = 0 for val in arr: self.append(va...
best-time-to-buy-and-sell-stock-iv
Best Python3 solution, using LinkedList and extremums of ascending intervals
timetoai
1
42
best time to buy and sell stock iv
188
0.381
Hard
2,979
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2834048/Python-solution-with-TC-greater-91
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: N = len(prices) dp = [0] * N for t in range(k): pos = -prices[0] profit = 0 for i in range(1,N): pos = max(pos, dp[i] - prices[i]) profit = max(profit, p...
best-time-to-buy-and-sell-stock-iv
Python solution with TC > 91%
user6230Om
0
1
best time to buy and sell stock iv
188
0.381
Hard
2,980
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2801668/Easy-Linear-order-Python-Solution
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: n=len(prices) prev=[0]*(2*k +1) # No need to write the base condition, as the dp is already initialized with for ind in range (n-1,-1,-1): temp=[0]*(2*k +1) for trans in range(2*k-1,-1,...
best-time-to-buy-and-sell-stock-iv
Easy Linear order Python Solution
Khan_Baba
0
3
best time to buy and sell stock iv
188
0.381
Hard
2,981
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2801667/Easy-Linear-order-Python-Solution
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: n=len(prices) prev=[0]*(2*k +1) # No need to write the base condition, as the dp is already initialized with for ind in range (n-1,-1,-1): temp=[0]*(2*k +1) for trans in range(2*k-1,-1,...
best-time-to-buy-and-sell-stock-iv
Easy Linear order Python Solution
Khan_Baba
0
1
best time to buy and sell stock iv
188
0.381
Hard
2,982
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2769150/Python-Memo
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: lenPrices = len(prices) @cache def dfs(i,holding,transactionCount): # End when you're at the end of prices or hit maximum transactions if i == lenPrices or transactionCount == k: r...
best-time-to-buy-and-sell-stock-iv
Python Memo
tupsr
0
4
best time to buy and sell stock iv
188
0.381
Hard
2,983
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2740283/Easy-Python-solution-one-pass-O(n*k)
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: cost = [100000] * k profit = [0] * k for price in prices: cost[0] = min(cost[0],price ) profit[0] = max(profit[0], price - cost[0]) for i in range(1,k): cost[i] = min(co...
best-time-to-buy-and-sell-stock-iv
Easy Python solution, one pass O(n*k)
adangert
0
8
best time to buy and sell stock iv
188
0.381
Hard
2,984
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2714360/Python-dp-beats-81-in-time-and-93-in-memory
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: n = len(prices) k = min(n//2,k) statelist = [[-prices[0],0] for i in range(k+1)] statelist[0] = [0,0] #st[j][m]表示前i天进行了j轮买卖,st[j][0]表示买,st[j][1]表示卖 #每次都是一开始拿i-1天的更新statelist[1][0],而第i天的statelist[1]...
best-time-to-buy-and-sell-stock-iv
Python dp beats 81% in time and 93% in memory
Ttanlog
0
7
best time to buy and sell stock iv
188
0.381
Hard
2,985
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2556069/Python-Beats-95-of-Accepted-(Easy)
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: if k == 0 or len(prices) == 0: return 0 min_price, profit = [float('inf')] * k, [float('-inf')] * k for price in prices: min_price[0] = min(min_price[0], price) profit[0] = m...
best-time-to-buy-and-sell-stock-iv
Python Beats 95% of Accepted ✅ (Easy)
Khacker
0
36
best time to buy and sell stock iv
188
0.381
Hard
2,986
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2431071/Python-Memoization-Solution
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: d = {} def bs(index, buyOrNotBuy, timesRemaining): if index >= len(prices): return 0 if timesRemaining == 0: return 0 # if we are able to buy the stock, if we al...
best-time-to-buy-and-sell-stock-iv
Python Memoization Solution
DietCoke777
0
29
best time to buy and sell stock iv
188
0.381
Hard
2,987
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2253610/Python-oror-Using-state-machine
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: if not prices or k == 0: return 0 transaction = [] transaction.append(-prices[0]) transaction.append(float(-inf)) for i in range(1,k): transaction.append(float(-inf)) t...
best-time-to-buy-and-sell-stock-iv
Python || Using state machine
dyforge
0
71
best time to buy and sell stock iv
188
0.381
Hard
2,988
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2172048/Easy-Readable-Python-(Top-Down-DP)
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: @cache def dp(i, transactions, holding = False): # base case if i == len(prices) or transactions == k: return 0 # we can only buy if we are not holding stock buy = helper...
best-time-to-buy-and-sell-stock-iv
Easy Readable Python (Top-Down DP)
kioola
0
69
best time to buy and sell stock iv
188
0.381
Hard
2,989
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2111260/Python-O(N*K)-runtime-and-O(N)-extra-space
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: size = len(prices) # max after buy mab = [] _max = float('-inf') # to start out with, max profit after a buy is the negated price for p in prices: _max = max(_max, -p) ...
best-time-to-buy-and-sell-stock-iv
Python O(N*K) runtime and O(N) extra space
aschade92
0
30
best time to buy and sell stock iv
188
0.381
Hard
2,990
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2060338/Python-or-Memoization
class Solution: def maxProfit(self, k: int, l: List[int]) -> int: n = len(l) d = {} def solve(i, s, t,mi): if t == 0: return 0 if d.get((i, s, t,mi)): return d[(i, s, t,mi)] if i == n: return 0 if...
best-time-to-buy-and-sell-stock-iv
Python | Memoization
Shivamk09
0
59
best time to buy and sell stock iv
188
0.381
Hard
2,991
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1789674/Python-easy-to-read-and-understand-or-Memoization
class Solution: def solve(self, prices, index, option, k): if index == len(prices) or k == 0: return 0 res = 0 if option == 0: buy = self.solve(prices, index + 1, 1, k) - prices[index] cool = self.solve(prices, index + 1, 0, k) res = max(buy, c...
best-time-to-buy-and-sell-stock-iv
Python easy to read and understand | Memoization
sanial2001
0
129
best time to buy and sell stock iv
188
0.381
Hard
2,992
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1789674/Python-easy-to-read-and-understand-or-Memoization
class Solution: def solve(self, prices, index, option, k): if index == len(prices) or k == 0: return 0 if (index, option, k) in self.dp: return self.dp[(index, option, k)] if option == 0: buy = self.solve(prices, index+1, 1, k) - prices[index] ...
best-time-to-buy-and-sell-stock-iv
Python easy to read and understand | Memoization
sanial2001
0
129
best time to buy and sell stock iv
188
0.381
Hard
2,993
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1769260/Python3-O(nk)-time-and-O(n)-space-complexity.-Simple-solution
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: n = len(prices) if not prices or k == 0: return 0 if 2 * k > n: res = 0 for i, j in zip(prices[1:], prices[:-1]): res += max(0, i - j) ...
best-time-to-buy-and-sell-stock-iv
Python3 O(nk) time and O(n) space complexity. Simple solution
MaverickEyedea
0
47
best time to buy and sell stock iv
188
0.381
Hard
2,994
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1696220/Python3-Top-Down-DP
class Solution: def maxProfit(self, k: int, A: List[int]) -> int: @cache def dfs(i, can, k): if i==len(A) or k==0: return 0 ans = dfs(i+1, can, k) # skip if not can: ans = max(ans, A[i]+dfs(i+1, 1, k-1)) # sell return max(ans, -A[i]+dfs(i+1, 0, k)) # b...
best-time-to-buy-and-sell-stock-iv
[Python3] Top Down DP
zhuzhengyuan824
0
76
best time to buy and sell stock iv
188
0.381
Hard
2,995
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1621849/Python3-solution-with-comments
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: if not k or not prices: return 0 matrix = [[0 for i in prices] for j in range(k+1)] #formula = we either take one of these options # 1- matrix[t][d] = matrix[t][d-1] which means we don't wanna sell a...
best-time-to-buy-and-sell-stock-iv
Python3 solution with comments
baraheyl
0
142
best time to buy and sell stock iv
188
0.381
Hard
2,996
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1476831/Python3-or-Dynamic-Programming
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: self.dp={} return self.dfs(0,0,prices,k) def dfs(self,day,own,prices,k): if k==0 or day==len(prices): return 0 if (day,own,k) in self.dp: return self.dp[(day,own,k)] if own: ...
best-time-to-buy-and-sell-stock-iv
[Python3] | Dynamic Programming
swapnilsingh421
0
72
best time to buy and sell stock iv
188
0.381
Hard
2,997
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/1354536/Python-Solution-Beats-95.38-Of-Python-Submissions
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: n=len(prices) if n==0:return 0 dp=[[0 for i in range(n)] for j in range(k+1)] for i in range(1,k+1): best=dp[i-1][0]-prices[0] for j in range(1,n): if prices[j]+best<dp[i][j...
best-time-to-buy-and-sell-stock-iv
Python Solution Beats 95.38% Of Python Submissions
reaper_27
0
187
best time to buy and sell stock iv
188
0.381
Hard
2,998
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/929364/Python-DP-concise-O(nk)-time-O(k)-space-solution
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: if k == 0: return 0 t0 = [0] * (k+1) t1 = [float('-inf')] * k for p in prices: for tr in range(k): t0[tr] = max(t0[tr], t1[tr] + p) t1[tr] = m...
best-time-to-buy-and-sell-stock-iv
Python DP concise O(nk) time O(k) space solution
modusV
0
64
best time to buy and sell stock iv
188
0.381
Hard
2,999