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) def next(self) -> int: return heapq.heappop(self.heap) def hasNext(self) -> bool: return self.heap!=[]
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 self.all = [] dfs(root) self.N = len(self.all) self.iter = 0 def next(self) -> int: v = self.all[self.iter] self.iter = self.iter + 1 return v def hasNext(self) -> bool: return self.iter < self.N
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 hasNext(self) -> bool: return self.n > 0 def inorderTraversal(self, root): if not root: return self.inorderTraversal(root.left) self.lst.append(root.val) self.inorderTraversal(root.right)
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: first = root last = root reorg(root.right) first, last = None, None reorg(root) self.cur = root = TreeNode(-float('inf')) self.cur.right = first def next(self) -> int: self.cur = self.cur.right return self.cur.val def hasNext(self) -> bool: if self.cur and self.cur.right: return True return False
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: return None nextNode = self.stack.pop() if nextNode.right: self.populateStack(nextNode.right) return nextNode.val def hasNext(self) -> bool: if not self.stack: return False return True
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(node.right) def next(self) -> int: if self.last is not None: ret, self.last = self.last, None return ret else: return next(self.gen) def hasNext(self) -> bool: if self.last is not None: return True elif self.over: return False else: try: self.last = next(self.gen) return True except: self.over = True return False
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.sort(reverse=True) def next(self) -> int: """ @return the next smallest number """ return self.vals.pop() def hasNext(self) -> bool: """ @return whether we have a next smallest number """ if len(self.vals) > 0: return True else: return False
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: """ @return the next smallest number """ self.iterator += 1 if self.iterator <= len(self.l) -1: return self.l[self.iterator] def hasNext(self) -> bool: """ @return whether we have a next smallest number """ if self.iterator + 1 <= len(self.l) -1: return True return False
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.right return node.val def hasNext(self) -> bool: return self.stack or self.node
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: self.stack.append(node) node = node.left return ans def hasNext(self) -> bool: return self.stack
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 next(self) -> int: return self.nodes.pop(0) def hasNext(self) -> bool: return len(self.nodes) > 0 # Your BSTIterator object will be instantiated and called as such: # obj = BSTIterator(root) # param_1 = obj.next() # param_2 = obj.hasNext()
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[i][j]) return max(1, min(fn(i+1, j), fn(i, j+1)) - dungeon[i][j]) return fn(0, 0)
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]) return ans[0]
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,-1,-1): if i==m-1 and j==n-1: dp[i][j]=max(1,1-dungeon[i][j]) elif i==m-1: dp[i][j]=max(1,dp[i][j+1]-dungeon[i][j]) elif j==n-1: dp[i][j]=max(1,dp[i+1][j]-dungeon[i][j]) else: dp[i][j]=max(1,min(dp[i][j+1],dp[i+1][j])-dungeon[i][j]) return dp[0][0]
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 # if we gain=dungeon[i][j]>0 then dp[i][j]=max(1,(min(dp[i+1][j],dp[i][j+1])-gain)) # if we damage=dungeon[i][j]<0 then dp[i][j]=-damage+min(dp[i+1][j],dp[i][j+1]) # if nothing empty=dungeon[i][j]=0 then dp[i][j]=min(dp[i+1][j],dp[i][j+1]) #no need to allocate extra storage, use dungeon to store dp values dungeon[-1][-1]=1 if dungeon[-1][-1]>=0 else 1-dungeon[-1][-1] for i in range(m-2,-1,-1): curr=dungeon[i][-1] if curr>0: dungeon[i][-1]=max(1,dungeon[i+1][-1]-curr) elif curr==0: dungeon[i][-1]=dungeon[i+1][-1] else: dungeon[i][-1]=-curr+dungeon[i+1][-1] for j in range(n-2,-1,-1): curr=dungeon[-1][j] if curr>0: dungeon[-1][j]=max(1,dungeon[-1][j+1]-curr) elif curr==0: dungeon[-1][j]=dungeon[-1][j+1] else: dungeon[-1][j]=-curr+dungeon[-1][j+1] for i in range(m-2,-1,-1): for j in range(n-2,-1,-1): curr=dungeon[i][j] if curr>0: dungeon[i][j]=max(1,(min(dungeon[i+1][j],dungeon[i][j+1])-curr)) elif curr==0: dungeon[i][j]=min(dungeon[i+1][j],dungeon[i][j+1]) else: dungeon[i][j]=-curr+min(dungeon[i+1][j],dungeon[i][j+1]) return dungeon[0][0]
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, j+1)) - self.grid[i][j] if anss > 0 : self.ans[i][j] = anss else: self.ans[i][j] = 1 return self.ans[i][j] def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: self.m = len(dungeon) self.n = len(dungeon[0]) self.grid = dungeon self.ans = [[-99999 for _ in range(self.n)] for _ in range(self.m)] return self.dp(0,0)
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]-dp[i][c]) for j in range(c-1, -1, -1): # bottom dp[r][j] = max(1, dp[r][j+1]-dp[r][j]) for i in range(r-1, -1, -1): for j in range(c-1, -1, -1): dp[i][j] = max(1, min(dp[i][j+1], dp[i+1][j])-dp[i][j]) return dp[0][0]
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] + 1 if i == m or j == n: return float('inf') if memo[i][j] != -1: return memo[i][j] res = min(dp(i, j+1), dp(i+1, j)) - dungeon[i][j] memo[i][j] = 1 if res <= 0 else res return memo[i][j] return dp(0,0)
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] = 1 dp[row][col-1] = 1 for i in range(row-1, -1, -1): for j in range(col-1, -1, -1): minHP = min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j] if minHP < 1: dp[i][j] = 1 else: dp[i][j] = minHP return dp[0][0]
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 valid(i, j): if i < 0 or j < 0 or i >= m or j >= n: return False return True for i in range(m - 1, -1, -1): for j in range(n - 1, -1, -1): if i == m - 1 and j == n - 1: continue health1 = float('inf') if not valid(i + 1, j) else memo[i + 1][j] health2 = float('inf') if not valid(i, j + 1) else memo[i][j + 1] tmp = min(health1, health2) - dungeon[i][j] memo[i][j] = tmp if tmp > 0 else 1 return memo[0][0]
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 + 1, j)) if i < m - 1 else -math.inf, min(0, helper(i, j + 1)) if j < n - 1 else -math.inf) return res + dungeon[i][j] return max(1, -helper(0, 0) + 1)
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 dp(grid, i, j): m = len(grid) # height of grid n = len(grid[0]) # width of grid if (i == m-1 and j == n-1): return 1 if grid[i][j] >= 0 else -grid[i][j] + 1 if (i == m or j == n): return sys.maxsize if memo[i][j] != -1: return memo[i][j] # resolve subproblem - finding the min hp to get to (i+1, j) and (i, j+1) and decrement current hp boost at (i, j) to find the min hp to get to (i, j) res = min(dp(grid, i+1, j), dp(grid, i, j+1)) - grid[i][j] memo[i][j] = 1 if res <= 0 else res return memo[i][j] return dp(dungeon, 0, 0)
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 >= width or nextCol >= height: return float('inf') nextCell = dp[nextRow][nextCol] return max(1, nextCell - currCell) for row in reversed(range(height)): for col in reversed(range(width)): currCell = dungeon[row][col] right_health = get_min_health(currCell, row, col+1) down_health = get_min_health(currCell, row+1, col) next_health = min(right_health, down_health) if next_health != float('inf'): min_health = next_health else: min_health = 1 if currCell >= 0 else (1-currCell) dp[row][col] = min_health return dp[0][0]
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 inf if (i, j) not in memo: temp = min(self.dp(dungeon, m, n, i + 1, j, memo), self.dp(dungeon, m, n, i, j + 1, memo)) - dungeon[i][j] memo[(i, j)] = 1 if temp <= 0 else temp return memo[(i, j)]
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 j in range(len(dungeon[0])-1,-1,-1): # in case dungeon[i][j] is positive and health become negative dp[i][j] = max(1,min(dp[i+1][j],dp[i][j+1]) - dungeon[i][j]) return dp[0][0]
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 4+1 2 6+0 11 5 0. 0 6 3+4 5 2 6 11 5 0 0 6 7 5 2 6 11 5 0 0. 6 """ n,m = len(li), len(li[0]) dp = [[None for i in range(m)] for i in range(n)] if li[-1][-1] >= 0: dp[-1][-1] = 0 else: dp[-1][-1] = abs(li[-1][-1]) + 1 #Populate last Column Values j = m-1 for i in range(n-2,-1, -1): reqHealth = dp[i+1][j] if li[i][j] >= 0: cHealth = li[i][j] print(cHealth, reqHealth) if cHealth >= reqHealth: dp[i][j] = 0 else: dp[i][j] = reqHealth - cHealth else: mandatoryHealthToSurvive = abs(li[i][j])+1 cHealth = 1 if cHealth >= reqHealth: dp[i][j] = mandatoryHealthToSurvive else: dp[i][j] = mandatoryHealthToSurvive + reqHealth - cHealth #Populate last Row Value i = n-1 for j in range(m-2,-1,-1): reqHealth = dp[i][j+1] if li[i][j] >= 0: cHealth = li[i][j] if cHealth >= reqHealth: dp[i][j] = 0 else: dp[i][j] = reqHealth - cHealth else: mandatoryHealthToSurvive = abs(li[i][j])+1 cHealth = 1 if cHealth >= reqHealth: dp[i][j] = mandatoryHealthToSurvive else: dp[i][j] = mandatoryHealthToSurvive + reqHealth - cHealth #Dp for i in range(n-2, -1, -1): for j in range(m-2, -1, -1): reqHealth = min(dp[i+1][j], dp[i][j+1]) if li[i][j] >= 0: cHealth = li[i][j] if cHealth >= reqHealth: dp[i][j] = 0 else: dp[i][j] = reqHealth - cHealth else: mandatoryHealthToSurvive = abs(li[i][j])+1 cHealth = 1 if cHealth >= reqHealth: dp[i][j] = mandatoryHealthToSurvive else: dp[i][j] = mandatoryHealthToSurvive + reqHealth - cHealth for i in dp: print(i) return max(1, dp[0][0])
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[-1][-1] = 1 else: dungeon[-1][-1] = abs(dungeon[-1][-1]) + 1 # Filling last column values for i in range(r-2,-1,-1): cell = dungeon[i][c-1] if cell > 0: dungeon[i][c-1] = max(dungeon[i+1][c-1] - cell, 1) else: dungeon[i][c-1] = dungeon[i+1][c-1] + abs(cell) #Filling last row values for j in range(c-2,-1,-1): cell = dungeon[r-1][j] if cell > 0: dungeon[r-1][j] = max(dungeon[r-1][j+1] - cell, 1) else: dungeon[r-1][j] = dungeon[r-1][j+1] + abs(cell) #General Case for i in range(r-2,-1,-1): for j in range(c-2,-1,-1): cell = dungeon[i][j] if cell > 0: dungeon[i][j] = max(min(dungeon[i+1][j], dungeon[i][j+1]) - cell, 1) else: dungeon[i][j] = min(dungeon[i+1][j], dungeon[i][j+1]) + abs(cell) return dungeon[0][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(dungeon[0])-1: dp[i][j] = min(dungeon[i][j], 0); continue val = max(dp[i][j+1] if j<len(dungeon[0])-1 else float("-inf"), dp[i+1][j] if i<len(dungeon)-1 else float("-inf")) dp[i][j] = 0 if dungeon[i][j] + val>0 else dungeon[i][j] + val return max(-dp[0][0], -dungeon[0][0], 0) + 1
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) if length > 1: middle = length //2 left_list = self.mergesort(nums[:middle]) right_list = self.mergesort(nums[middle:]) nums = self.merge(left_list,right_list) return nums def merge(self,list1,list2): result = [] l1 = deque(list1) l2 = deque(list2) while l1 and l2: if self.compare(l1[0],l2[0]): result.append(l1[0]) l1.popleft() else: result.append(l2[0]) l2.popleft() result.extend(l1 or l2) return result
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_to_key(compare)) return str(int(str(''.join(nums))))
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 + other.obj < other.obj + self.obj def __eq__(self, other): return self.obj == other.obj return cmp return "".join(sorted(map(str, nums), key=fn(), reverse=True)).lstrip("0") or "0"
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 "".join(sorted(map(str, nums), key=cmp_to_key(cmp), reverse=True)).lstrip("0") or "0"
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): return '0' for i in range(len(nums)): for j in range(i + 1, len(nums)): if int(nums[j] + nums[i]) > int(nums[i] + nums[j]): nums[i], nums[j] = nums[j], nums[i] return ''.join(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.append(a1[l]) l += 1 else: res.append(a2[r]) r += 1 if l < len(a1): res += a1[l:] if r < len(a2): res += a2[r:] return res if len(arr) == 1: return arr mid = len(arr)//2 l1, l2 = mergesort(arr[:mid]), mergesort(arr[mid:]) return merge_lists(l1, l2) if not nums: return '0' res = mergesort([str(x) for x in nums]) return '0' if res[0] == '0' else ''.join(res)
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] + nums[j]): nums[j], nums[j + 1] = nums[j + 1], nums[j] # If all zero if nums[0] == '0': return '0' return ''.join(nums)
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): ans = [] i = l j = m+1 while i <= m and j <= r: if int(arr[i]+arr[j]) > int(arr[j]+arr[i]): ans.append(arr[i]) i += 1 else: ans.append(arr[j]) j += 1 while i <= m: ans.append(arr[i]) i+=1 while j <= r: ans.append(arr[j]) j+=1 for i in range(len(ans)): arr[l+i] = ans[i] arr = [str(num) for num in nums] mergeSort(arr, 0, len(arr)-1) return "0" if arr and arr[0] == "0" else "".join(arr)
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): return (int(nums[x]+nums[y])) > (int(nums[y]+nums[x])) #this function will only return when (int(nums[x]+nums[y])) > (int(nums[y]+nums[x])) is True for x in range(len(nums)-1): y=x+1 while x<len(nums) and y<len(nums): if not compare(x,y): nums[x],nums[y]=nums[y],nums[x] y+=1 return "".join(nums)
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>0 and str(n)+res[j-1]>res[j-1]+str(n): j-=1 res.insert(j,str(n)) else: res.append(str(n)) ans="".join(res) if int(ans)==0: return '0' return "".join(res)
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 for j in range(len(nums)-i-1): if len(nums[j]) == len(nums[j+1]): continue if int(nums[j]+nums[j+1]) < int(nums[j+1]+nums[j]): nums[j],nums[j+1]=nums[j+1],nums[j] flag = True if not flag: break ans = str(int("".join(nums))) # to strip out all the extra zeroes on the left return ans
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(comp)) return str(int(''.join(nums)))
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]) elif(x<y): rev.append(nums[i]) else: rev[n-1] = rev[n-1]+nums[i] return str(int(''.join(rev[::-1])))
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: ans.append(left[i]) i += 1 else: ans.append(right[j]) j += 1 ans += left[i:] ans += right[j:] return ans def mergeSort(arr): if len(arr)<=1: return arr mid = len(arr)//2 left = mergeSort(arr[:mid]) right = mergeSort(arr[mid:]) return merge(left,right) for i in range(len(nums)): nums[i] = str(nums[i]) res = mergeSort(nums) return str(int("".join(res)))
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 in range(len(nums)): for j in range(i+1,len(nums)): if not self.compare(nums[i],nums[j]): nums[i],nums[j]=nums[j],nums[i] return ''.join(map(str,nums))
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 will be encouraging
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 res.append(sequence) else: seen[sequence] = False return res
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 i >= 9: if hs in seen: ans.add(s[i-9:i+1]) seen.add(hs) return ans
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 in result: result.append(c) else: sample.append(c) print(sample) print(result) return result
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 temp[ele]>1: ans.append(ele) return ans
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) memory[subseq] += 1 return res
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 elif s[i] == 'T': nums[i] = 3 seen = set() res = set() digitPos = 10 digitBase = 4 hiDigit = pow(digitBase, digitPos - 1) left, right = 0, 0 windowHash = 0 while (right < len(s)): # expand right boundary by 1 windowHash = windowHash * digitBase + nums[right] right += 1 if (right - left >= digitPos): if (windowHash in seen): res.add(s[left:right]) else: seen.add(windowHash) # shrink left boundary by 1 windowHash = windowHash - nums[left] * hiDigit left += 1 return res
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: res.append(temp) mapp[temp] = a+1 else: mapp[temp] = 1 return res
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 in dna_dict: if dna_dict[dna] > 1: ans.append(dna) return ans
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+10]) return res
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: res.append(curr) else: visited.add(curr) return list(set(res))
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 range(len(s)-9): if s[i:i+10] in seen: rep.add(s[i:i+10]) else: seen.add(s[i:i+10]) return rep
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(k + 1)] for price in prices: for i in range(1, k + 1): # price - dp[i - 1][1] is how much you need to spend # i.e use the profit you earned from previous transaction to buy the stock # we want to minimize it dp[i][0] = min(dp[i][0], price - dp[i - 1][1]) # price - dp[i][0] is how much you can achieve from previous min cost # we want to maximize it dp[i][1] = max(dp[i][1], price - dp[i][0]) # return max profit at most k transactions # or you can write `return dp[-1][1]` return dp[k][1]
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 - 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-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)): most = max(ans[i], most + prices[i] - prices[i-1]) ans[i] = max(ans[i-1], most) return ans[-1]
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) return sell[-1]
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[i] = min(dp_cost[i], price) dp_profit[i] = max(dp_profit[i], price-dp_cost[i]) else: dp_cost[i] = min(dp_cost[i], price - dp_profit[i-1]) dp_profit[i] = max(dp_profit[i], price - dp_cost[i]) return dp_profit[-1]
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): if(buy): profit = max(-prices[ind]+ dp[ind+1][0][cap] , 0 + dp[ind+1][1][cap]) else: profit = max(prices[ind] + dp[ind+1][1][cap-1], 0 + dp[ind+1][0][cap]) dp[ind][buy][cap] = profit ind -= 1 return dp[0][1][k]
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): for cap in range(1,k+1): if(buy): profit = max(-prices[ind]+ after[0][cap] , 0 + after[1][cap]) else: profit = max(prices[ind] + after[1][cap-1], 0 + after[0][cap]) curr[buy][cap] = profit ind -= 1 after = [x for x in curr] return after[1][k]
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, holding) do_something = 0 if holding: # sell do_something = prices[i] + dp(i+1, trxn_remaining-1, False) else: # buy do_something = -prices[i] + dp(i+1, trxn_remaining, True) return max(do_nothing, do_something) return dp(0, k, False)
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 = dp[i+1][trxn_remaining][holding] if holding: # sell stock do_something = prices[i] + dp[i+1][trxn_remaining-1][0] else: # buy stock do_something = -prices[i] + dp[i+1][trxn_remaining][1] # recurrence relation dp[i][trxn_remaining][holding] = max( do_nothing, do_something) return dp[0][k][0]
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(profit[i], price - cost[i]) return profit[k]
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(val) def append(self, val): if not self.head: self.head = self.tail = Node(val) else: self.tail.r = Node(val, l=self.tail) self.tail = self.tail.r self.count += 1 def merge(self): worst = self.head if self.head.score < self.head.r.score else self.head.r best = self.head bs = (self.head.r.v[1] - self.head.v[0]) - (self.head.score + self.head.r.score) node = self.head.r while node.r: if worst.score > node.r.score: worst = node.r cur = (node.r.v[1] - node.v[0]) - (node.score + node.r.score) if cur > bs: best = node bs = cur node = node.r # we can merge two intervals into one or delete one interval if bs > - worst.score: node = best rnode = node.r node.r = rnode.r if rnode.r: rnode.r.l = node else: self.tail = node node.v[1] = rnode.v[1] node.score = node.v[1] - node.v[0] del rnode else: if not worst.l: self.head = worst.r else: worst.l.r = worst.r if not worst.r: self.tail = worst.l else: worst.r.l = worst.l del worst self.count -= 1 def __len__(self): return self.count def __repr__(self): arr = [] node = self.head while node: arr.append(node.v) node = node.r return str(arr) def sum(self): ret = 0 node = self.head while node: ret += node.score node = node.r return ret class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: if k == 0: return 0 # store ascending intervals in format (low, high) lh = LinkedList() i = 1 while i < len(prices): # skip descending while i < len(prices) and prices[i] < prices[i - 1]: i += 1 if i == len(prices): break low = prices[i - 1] while i < len(prices) and prices[i] >= prices[i - 1]: i += 1 if prices[i - 1] != low: lh.append([low, prices[i - 1]]) # print(lh) # stacking ascending sequences to fit in k intervals while len(lh) > k: lh.merge() # print(lh) return lh.sum()
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, pos + prices[i]) dp[i] = profit return dp[-1]
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,-1): if trans%2==0:#buy temp[trans]=max((-prices[ind]+prev[trans+1]) ,prev[trans]) else: temp[trans]=max((prices[ind]+prev[trans+1]) ,prev[trans]) prev=temp return prev[0]
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,-1): if trans%2==0:#buy temp[trans]=max((-prices[ind]+prev[trans+1]) ,prev[trans]) else: temp[trans]=max((prices[ind]+prev[trans+1]) ,prev[trans]) prev=temp return prev[0]
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: return 0 # If you're currently holding, you can either sell (+price[i]) or keep holding if holding: holdingAndSkip = dfs(i+1,True,transactionCount) holdingAndTake = dfs(i+1,False,transactionCount+1)+prices[i] return max(holdingAndSkip,holdingAndTake) # If you're not holding, you can buy (-price[i]) or wait for another day to buy else: notHoldingAndSkip = dfs(i+1,False,transactionCount) notHoldingAndTake = dfs(i+1,True,transactionCount)-prices[i] return max(notHoldingAndSkip,notHoldingAndTake) return dfs(0,False,0)
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(cost[i],price - profit[i-1] ) profit[i] = max(profit[i], price - cost[i]) return profit[k-1]
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][0]更新好后用第i天的statelist[1][0]更新第i天的statelist[1][1],用第i天的statelist[1][1]更新第i天的statelst[2][0],用第i天的statelist[2][0]更新第i天的statelst[2][1],依次类推 for i in range(1,n): for j in range(1,len(statelist)): statelist[j][0]=max(statelist[j][0],statelist[j-1][1]-prices[i]) statelist[j][1]=max(statelist[j][1],statelist[j][0]+prices[i]) return statelist[k][1] # statelist = [-prices[0] if i%2==1 else 0 for i in range(k*2+1)] # #statelist[j]表示前i天进行j次买+卖的的最大利润 # for i in range(1,n): # for j in range(1,len(statelist)): # if j==1: statelist[j]=max(statelist[j],-prices[i]) # else: # if j%2==0: # statelist[j]=max(statelist[j],statelist[j-1]+prices[i]) # else: # statelist[j]=max(statelist[j],statelist[j-1]-prices[i]) # return statelist[-1] #思路来源:买卖股票3 # dp1 = -prices[0] #前i天恰好进行了一次买的最大利润 # dp2 = 0 #前i天恰好进行了一次买卖的最大利润 # dp3 = -prices[0] #前i天恰好进行了一次买卖加一次买的最大利润 # dp4 = 0 #前i天恰好进行了两次买卖的最大利润 # for i in range(1,n): # dp1 = max(dp1,-prices[i]) # dp2 = max(dp2, dp1+prices[i]) # dp3 = max(dp3, dp2-prices[i]) # dp4 = max(dp4,dp3+prices[i]) # return dp4
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] = max(profit[0], price - min_price[0]) for i in range(1, k): min_price[i] = min(min_price[i], price - profit[i-1]) profit[i] = max(profit[i], price - min_price[i]) return profit[k-1]
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 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", timesRemaining) not in d: profit = -1 * prices[index] + bs(index+1, "notBuy", timesRemaining) else: profit = -1 * prices[index] + d[(index+1, "notBuy", timesRemaining)] # if buy later, not now at this index if (index+1, "buy", timesRemaining) not in d: profit1 = bs(index+1, "buy", timesRemaining) else: profit1 = d[(index+1, "buy",timesRemaining)] d[(index, buyOrNotBuy,timesRemaining)] = max(profit, profit1) return d[(index, buyOrNotBuy,timesRemaining)] else: # sell stock, if we sell 2nd argument is buy # sell stock at this index if (index+1, "buy",timesRemaining) not in d: profit = prices[index] + bs(index+1, "buy", timesRemaining-1) else: profit = prices[index] + d[(index+1, "buy",timesRemaining-1)] # sell stock not at this index now, sell it later if (index+1, "notBuy",timesRemaining) not in d: profit1 = bs(index+1, "notBuy",timesRemaining) else: profit1 = d[(index+1, "notBuy",timesRemaining)] d[(index, buyOrNotBuy,timesRemaining)] = max(profit, profit1) return d[(index, buyOrNotBuy, timesRemaining)] return bs(0, "buy", k)
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)) transaction.append(float(-inf)) for price in prices: transaction[0] = max(transaction[0], -price) transaction[1] = max(transaction[1], transaction[0]+price) for t in range(2,len(transaction)): if t % 2 == 0: transaction[t] = max(transaction[t], transaction[t-1]-price) else: transaction[t] = max(transaction[t], transaction[t-1]+price) return transaction[-1]
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(i + 1, transactions, True) - prices[i] if not holding else 0 # we can only sell if we are holding stock sell = helper(i + 1, transactions + 1, False) + prices[i] if holding else 0 # each day, we have the option to do nothing no_action = helper(i + 1, transactions, holding) return max(buy, sell, no_action) return dp(0, 0)
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) mab.append(_max) # max after a buy then sell mabs = [float('-inf') for _ in range(size)] max_transactions = min(size//2, k) res = 0 for _ in range(max_transactions): # calculate mabs first, since we want to find out the max profit after a previous buy for i in range(1, size): p = prices[i] mabs[i] = max(mabs[i-1], mab[i-1] + p) res = max(res, mabs[i]) # mab then follows from the values calculated above in mabs for i in range(1, size): p = prices[i] mab[i] = max(mab[i], mab[i-1], mabs[i-1]-p) return res
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 s: if l[i]<mi: d[(i,s,t,mi)] = solve(i+1,s,t,l[i]) return d[(i,s,t,mi)] else: d[(i,s,t,mi)] = max(l[i]-mi+solve(i+1,0,t-1,float("inf")),solve(i+1,s,t,mi)) return d[(i, s, t,mi)] d[(i,s,t,mi)] = max(solve(i+1,1,t,l[i]),solve(i+1,0,t,mi)) return d[(i, s, t,mi)] return solve(0,0,k,float("inf"))
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, cool) if option == 1: sell = self.solve(prices, index + 1, 0, k - 1) + prices[index] cool = self.solve(prices, index + 1, 1, k) res = max(sell, cool) return res def maxProfit(self, k: int, prices: List[int]) -> int: return self.solve(prices, 0, 0, k)
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] cool = self.solve(prices, index+1, 0, k) self.dp[(index, option, k)] = max(buy, cool) if option == 1: sell = self.solve(prices, index+1, 0, k-1) + prices[index] cool = self.solve(prices, index+1, 1, k) self.dp[(index, option, k)] = max(sell, cool) return self.dp[(index, option, k)] def maxProfit(self, k: int, prices: List[int]) -> int: self.dp = {} return self.solve(prices, 0, 0, k)
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) return res even_profits = [0 for d in prices] odd_profits = [0 for d in prices] for t in range(1, k+1): max_sofar = float('-inf') if t % 2 == 1: current_profit = odd_profits previous_profit = even_profits else: current_profit = even_profits previous_profit = odd_profits for d in range(1, n): max_sofar = max(max_sofar, previous_profit[d-1] - prices[d-1]) current_profit[d] = max(max_sofar + prices[d], current_profit[d-1]) return even_profits[-1] if k % 2 == 0 else odd_profits[-1] ```
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)) # buy return dfs(0, 1, k)
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 and we wanna keep # the current profit #2- matrix[t][d] = max(matrix[x-1][d] - prices[x]) which means we bought the #stock at prices[x] and we sell at in prices[d] and add to it the profit we had #before buying stock at prices[x] for i in range(len(prices)): matrix[0][i] = 0 result = 0 for transaction in range(1,len(matrix)): best_value = float("-inf") # re-initialize because at each transaction the profits may changes and so we want to re-calculate best profit again for day in range(1,len(matrix[0])): best_value = max(best_value, matrix[transaction-1][day-1]-prices[day-1]) matrix[transaction][day] = max(matrix[transaction][day-1], best_value+prices[day]) return matrix[-1][-1]
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: p1=prices[day]+self.dfs(day+1,0,prices,k-1) p2=self.dfs(day+1,1,prices,k) else: p1=-prices[day]+self.dfs(day+1,1,prices,k) p2=self.dfs(day+1,0,prices,k) self.dp[(day,own,k)]=max(p1,p2) return self.dp[(day,own,k)]
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-1]:dp[i][j]=dp[i][j-1] else:dp[i][j]=prices[j]+best if dp[i-1][j]-prices[j]>best:best=dp[i-1][j]-prices[j] return dp[-1][-1]
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] = max(t1[tr], t0[tr-1] - p) return t0[-2]
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