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/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2094334/Beginner-Friendly-Python-3-Solution
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: ds = set() # to hold all vals i=0 while (i+k<=len(s)): ds.add(s[i:i+k]) i+=1; if len(ds) == 2**k: # if no. of elems == 2^n (n=no. of bits) return True return False
check-if-a-string-contains-all-binary-codes-of-size-k
Beginner Friendly Python-3 Solution
Nishhant
0
9
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,800
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2093457/Python3-Solution-with-using-hashset
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: _set = set() for i in range(len(s) - k + 1): _set.add(s[i:i+k]) return 2**k == len(_set)
check-if-a-string-contains-all-binary-codes-of-size-k
[Python3] Solution with using hashset
maosipov11
0
8
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,801
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2093185/Python-Simple-Python-Solution-Using-Hashset
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: distinct_substring = set() for i in range(len(s)-k+1): num = s[i:i+k] if num not in distinct_substring: distinct_substring.add(num) if len(distinct_substring) == 2**k: return True else: return False
check-if-a-string-contains-all-binary-codes-of-size-k
[ Python ] βœ…βœ… Simple Python Solution Using Hashset βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
0
26
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,802
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2093109/Python-or-Set
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: d = set() for i in range(len(s)-k+1): d.add(s[i:i+k]) if len(d) == 2**k: return True return False
check-if-a-string-contains-all-binary-codes-of-size-k
Python | Set
Shivamk09
0
8
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,803
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2092575/Simple-Python-solution-with-explanation
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: d = {} # Save all strings with length k in dict. So, we can look any string up with O(1) for i in range(k, len(s) + 1): sect = s[i-k:i] d[sect] = d.get(sect,0) + 1 count = 0 for i in range(2 ** k): # Loop to 2 ** k can generate. every possible combination of 0 1 in binary. ex: (when k=3) 0,1,10,11,100,101,110,111 b = bin(i)[2:] check = "0" * (k-len(b)) + b # add 0s at the front if length is not equal to k ex: (when k=4) 10 => 0010 if check in d: # Existing inside dictionary = Existing inside string (s) count += 1 return count == 2 ** k # There should be 2 ** k combination in total. count == 2 ** k means every single one of them was inside dict, hence True.
check-if-a-string-contains-all-binary-codes-of-size-k
βœ… Simple Python solution with explanation
Eba472
0
22
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,804
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/1860278/Python-or-beats-speed-94
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: d = {} for i in range(len(s) - k + 1): cur = s[i:i+k] if cur not in d: d[cur] = 1 return len(d) == 2 ** k
check-if-a-string-contains-all-binary-codes-of-size-k
Python | beats speed 94%
Bec1l
0
61
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,805
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/1705993/Python3-solution-using-set
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: m = set() for i in range(len(s)-k+1): m.add(int(s[i:i+k],2)) for i in range(2**k): if i not in m: return False return True
check-if-a-string-contains-all-binary-codes-of-size-k
Python3 solution using set
EklavyaJoshi
0
35
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,806
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/1696022/Faster-than-40-sliding-windown
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: binaries=set() l=0 r=k curr_set=set() while(r<=len(s)): curr_set.add(s[l:r]) if(len(curr_set)==2**k): return(True) exit() l+=1 r+=1 return(False)
check-if-a-string-contains-all-binary-codes-of-size-k
Faster than 40%, sliding windown
naren_nadig
0
47
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,807
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/1106339/PythonPython3-Check-If-a-String-Contains-All-Binary-Codes-of-Size-K
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: uniq = set() i = 0 j = i + k exp_len = 2**k while j<= len(s): # print(uniq, s[i:j]) if len(uniq) < exp_len: uniq.add(s[i:j]) else: return True i += 1 j += 1 if len(uniq) == exp_len: return True else: return False
check-if-a-string-contains-all-binary-codes-of-size-k
[Python/Python3] Check If a String Contains All Binary Codes of Size K
newborncoder
0
66
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,808
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/1105714/Simple-solution-in-Python-using-a-hashmap
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: substrings = dict() n = len(s) for i in range(0, n - k + 1): substrings[s[i: i + k]] = True # print(substrings) for i in range(0, 2 ** k): b = bin(i)[2:].zfill(k) # print(i, b) if b not in substrings: return False return True
check-if-a-string-contains-all-binary-codes-of-size-k
Simple solution in Python using a hashmap
amoghrajesh1999
0
18
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,809
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/661614/Python-Easy-to-understand-sliding-window-%2B-Set
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: all_set = set() for i in range(k, len(s)+1): all_set.add(s[i-k:i]) return len(all_set) == 2**k
check-if-a-string-contains-all-binary-codes-of-size-k
Python - Easy to understand sliding window + Set
sudnar
0
29
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,810
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/660655/Python3-one-line-brute-force
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: ans = {s[i:i+k] for i in range(len(s)-k+1)} return len(ans) == 1 << k
check-if-a-string-contains-all-binary-codes-of-size-k
[Python3] one-line brute force
ye15
0
32
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,811
https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/660655/Python3-one-line-brute-force
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: return all(bin(i)[2:].zfill(k) in s for i in range(2**k))
check-if-a-string-contains-all-binary-codes-of-size-k
[Python3] one-line brute force
ye15
0
32
check if a string contains all binary codes of size k
1,461
0.568
Medium
21,812
https://leetcode.com/problems/course-schedule-iv/discuss/2337629/Python3-or-Solved-Using-Ancestors-of-every-DAG-Graph-Node-approach(Kahn's-Algo-BFS)
class Solution: def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: #Let m = len(prereqs) and z = len(queries) #Time: O(m + n + n*n + z) -> O(n^2) #Space: O(n*n + n + n*n + n + z) -> O(n^2) #process the prerequisites and build an adjacency list graph #where edges go from prerequisite to the course that depends on the prereq! n = numCourses #Adjacency List graph! adj = [set() for _ in range(n)] #indegrees array! indegrees = [0] * n #tell us every ith node's set of ancestors or all prereqs to take ith course! ancestors = [set() for _ in range(n)] #iterate through prereqs and update indegrees array as well as the adj list! for i in range(len(prerequisites)): prereq, main = prerequisites[i][0], prerequisites[i][1] adj[prereq].add(main) indegrees[main] += 1 queue = deque() #iterate through the indegrees array and add all courses that have no #ancestors(no prerequisites to take it!) for a in range(len(indegrees)): #ath course can be taken without any prereqs -> first to be processed in #the Kahn's BFS algo! if(indegrees[a] == 0): queue.append(a) #proceed with Kahn's algo! while queue: cur_course = queue.pop() neighbors = adj[cur_course] for neighbor in neighbors: #neighbor has one less incoming edge! indegrees[neighbor] -= 1 #current course is a prerequisite to every neighboring node! ancestors[neighbor].add(cur_course) #but also, all prereqs of cur_course is also indirectly a prereq #to each and every neighboring courses! ancestors[neighbor].update(ancestors[cur_course]) #if neighboring node suddenly becomes can take with no prereqs, #add it to the queue! if(indegrees[neighbor] == 0): queue.append(neighbor) #once the algorithm ends, our ancestors array will have info regarding #prerequisites in order to take every course from 0 to n-1! output = [] for query in queries: prereq2, main2 = query[0], query[1] all_prereqs = ancestors[main2] #check if prereq2 is an ancestor or required prereq course to take main2! if(prereq2 in all_prereqs): output.append(True) continue else: output.append(False) return output
course-schedule-iv
Python3 | Solved Using Ancestors of every DAG Graph Node approach(Kahn's Algo BFS)
JOON1234
1
28
course schedule iv
1,462
0.489
Medium
21,813
https://leetcode.com/problems/course-schedule-iv/discuss/948893/Python3-Solution-using-dfs
class Solution: def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: if not prerequisites: return [False]*len(queries) graph = collections.defaultdict(list) for i,j in prerequisites: graph[i].append(j) def dfs(source,distance,visited): visited[source] = 1 if source == distance: return True for i in graph[source]: if(visited.get(i) is None): if(dfs(i,distance,visited)): return True return False ans = [] for i,j in queries: if j in graph[i]: ans.append(True) else: visited = {} ans.append(dfs(i,j,visited)) return ans
course-schedule-iv
Python3 Solution using dfs
swap2001
0
60
course schedule iv
1,462
0.489
Medium
21,814
https://leetcode.com/problems/course-schedule-iv/discuss/917605/Python3-BFS-(easy)
class Solution: def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: def bfs(root, dest): stack = deque([root]) seen = set() while stack: item = stack.popleft() if item == dest: return True for child in graph[item]: if child not in seen: seen.add(child) stack.append(child) return False graph = {i: [] for i in range(n)} for a, b in prerequisites: graph[a].append(b) res = [] for a, b in queries: res.append(bfs(a, b)) return res
course-schedule-iv
Python3 BFS (easy)
ermolushka2
0
108
course schedule iv
1,462
0.489
Medium
21,815
https://leetcode.com/problems/cherry-pickup-ii/discuss/1674033/Python3-DYNAMIC-PROGRAMMING-(*)-Explained
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: rows, cols = len(grid), len(grid[0]) dp = [[[0]*(cols + 2) for _ in range(cols + 2)] for _ in range(rows + 1)] def get_next_max(row, col_r1, col_r2): res = 0 for next_col_r1 in (col_r1 - 1, col_r1, col_r1 + 1): for next_col_r2 in (col_r2 - 1, col_r2, col_r2 + 1): res = max(res, dp[row + 1][next_col_r1 + 1][next_col_r2 + 1]) return res for row in reversed(range(rows)): for col_r1 in range(min(cols, row + 2)): for col_r2 in range(max(0, cols - row - 1), cols): reward = grid[row][col_r1] + grid[row][col_r2] if col_r1 == col_r2: reward /= 2 dp[row][col_r1 + 1][col_r2 + 1] = reward + get_next_max(row, col_r1, col_r2) return dp[0][1][cols]
cherry-pickup-ii
❀ [Python3] DYNAMIC PROGRAMMING (*Β΄βˆ‡ο½€)οΎ‰, Explained
artod
14
506
cherry pickup ii
1,463
0.701
Hard
21,816
https://leetcode.com/problems/cherry-pickup-ii/discuss/660627/Python3-7-line-top-down-dp
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) @lru_cache(None) def fn(i, j, jj): """Return max cherries picked so far when two robots are at (i, j) and (i, jj)""" if not (0 <= i < m and 0 <= j < n and 0 <= jj < n) or j > i or jj < n-1-i or jj < j: return 0 if i == 0: return grid[0][0] + grid[0][n-1] return grid[i][j] + (jj != j) * grid[i][jj] + max(fn(i-1, k, kk) for k in range(j-1, j+2) for kk in range(jj-1, jj+2)) return max(fn(m-1, j, jj) for j in range(n) for jj in range(n))
cherry-pickup-ii
[Python3] 7-line top-down dp
ye15
3
130
cherry pickup ii
1,463
0.701
Hard
21,817
https://leetcode.com/problems/cherry-pickup-ii/discuss/660627/Python3-7-line-top-down-dp
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) @lru_cache(None) def fn(i, j, k): """Return maximum cherries picked when two robots start at (i, j) and (i, k).""" if not 0 <= j <= k < n: return -inf if i == m: return 0 ans = grid[i][j] + (j!=k) * grid[i][k] return ans + max(fn(i+1, jj, kk) for jj in (j-1, j, j+1) for kk in (k-1, k, k+1)) return fn(0, 0, n-1)
cherry-pickup-ii
[Python3] 7-line top-down dp
ye15
3
130
cherry pickup ii
1,463
0.701
Hard
21,818
https://leetcode.com/problems/cherry-pickup-ii/discuss/1674529/Python3-Backtracking-with-cache-5-liner
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: @cache def backtracking(row,r1,r2): if row < len(grid) and 0 <= r1 < r2 < len(grid[0]): return grid[row][r1]+grid[row][r2]+ max(backtracking(row+1,r1+d1,r2+d2) for d1,d2 in itertools.product((-1,0,1),(-1,0,1))) return 0 return backtracking(0,0,len(grid[0])-1)
cherry-pickup-ii
Python3 Backtracking with cache 5-liner
pknoe3lh
2
48
cherry pickup ii
1,463
0.701
Hard
21,819
https://leetcode.com/problems/cherry-pickup-ii/discuss/1674363/Easy-oror-Intuition-oror-GO-As-Question-says
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) @lru_cache(None) def dfs(r,c1,c2): if r==m: return 0 ch = grid[r][c1] if c1==c2 else grid[r][c1]+grid[r][c2] res = 0 for p in range(c1-1,c1+2): for q in range(c2-1,c2+2): if 0<=p<n and 0<=q<n: res = max(res,dfs(r+1,p,q)) return ch+res return dfs(0,0,n-1)
cherry-pickup-ii
πŸ“ŒπŸ“Œ Easy || Intuition || GO As Question says 🐍
abhi9Rai
2
82
cherry pickup ii
1,463
0.701
Hard
21,820
https://leetcode.com/problems/cherry-pickup-ii/discuss/1674799/Python3-DP-w-symmetry-optimization
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: @cache def maxCherries(i, j1, j2): # optimization by symmetry if j1 > j2: return maxCherries(i, j2, j1) # return 0 if either robot goes out of bounds if i == len(grid) or j1 == -1 or j2 == len(grid[0]): return 0 # maximize cherries over all 9 possible robot movements best = max(maxCherries(i+1, j1+d1, j2+d2) for d1 in range(-1, 2) for d2 in range(-1, 2)) # return cherries that robots are occupying + best return best + (grid[i][j1] + grid[i][j2]) if j1 != j2 else (grid[i][j1]) return maxCherries(0, 0, len(grid[0])-1)
cherry-pickup-ii
[Python3] DP w/ symmetry optimization
vscala
1
35
cherry pickup ii
1,463
0.701
Hard
21,821
https://leetcode.com/problems/cherry-pickup-ii/discuss/2452745/Python-Simple-Python-Solution-100-Optimal-Solution
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) dp = [[[-1 for i in range(m+1)] for j1 in range(n+1)] for j2 in range(n+1)] print(dp) def sol(i, j1, j2): if j1 < 0 or j2 < 0 or j1 >= m or j2 >= m: return -1e8 if dp[i][j1][j2] != -1: return dp[i][j1][j2] if i == n-1: if j1 == j2 : return grid[i][j1] else: return grid[i][j1] + grid[i][j2] maxi = -1e8 for a in range(-1 , 2): for b in range(-1, 2): temp = 0 if j1 == j2 : temp =grid[i][j1] else: temp = grid[i][j1] + grid[i][j2] temp += sol(i+1, j1+a, j2+b) maxi = max(maxi, temp) dp[i][j1][j2] = maxi return maxi return sol(0 , 0, m-1)
cherry-pickup-ii
[ Python ] βœ… Simple Python Solution βœ…βœ… βœ…100% Optimal Solution
vaibhav0077
0
23
cherry pickup ii
1,463
0.701
Hard
21,822
https://leetcode.com/problems/cherry-pickup-ii/discuss/2452745/Python-Simple-Python-Solution-100-Optimal-Solution
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) dp = [[[-1 for i in range(m+1)] for j1 in range(m+1)] for j2 in range(n)] # Base Case for j1 in range(m): for j2 in range(m): if j1 == j2: dp[n-1][j1][j2] = grid[n-1][j1] else: aa = grid[n-1][j1] + grid[n-1][j2] dp[n-1][j1][j2] = aa # Logic for i in range(n-2, -1, -1): for j1 in range(m): for j2 in range(m): maxi = -1e8 for a in range(-1 , 2): for b in range(-1, 2): temp = 0 if j1 == j2 : temp =grid[i][j1] else: temp = grid[i][j1] + grid[i][j2] temp += dp[i+1][j1+a][j2+b] maxi = max(maxi, temp) dp[i][j1][j2] = maxi return dp[0][0][m-1]
cherry-pickup-ii
[ Python ] βœ… Simple Python Solution βœ…βœ… βœ…100% Optimal Solution
vaibhav0077
0
23
cherry pickup ii
1,463
0.701
Hard
21,823
https://leetcode.com/problems/cherry-pickup-ii/discuss/2452745/Python-Simple-Python-Solution-100-Optimal-Solution
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) dp = [[[-1 for i in range(m+1)] for j1 in range(m+1)] for j2 in range(n)] prev = [[-1 for i in range(m)] for j1 in range(m)] cur = [[-1 for i in range(m)] for j1 in range(m)] # Base Case for j1 in range(m): for j2 in range(m): if j1 == j2: prev[j1][j2] = grid[n-1][j1] else: prev[j1][j2] = grid[n-1][j1] + grid[n-1][j2] # Logic for i in range(n-2, -1, -1): for j1 in range(m): for j2 in range(m): maxi = -1e8 for a in range(-1 , 2): for b in range(-1, 2): temp = 0 if j1 == j2 : temp = grid[i][j1] else: temp = grid[i][j1] + grid[i][j2] if j1 + a >=0 and j1 + a < m and j2+b >= 0 and j2+b< m : temp = temp + prev[j1+a][j2+b] else: temp = -1e8 maxi = max(maxi, temp) cur[j1][j2] = maxi prev = copy.deepcopy(cur) return prev[0][m-1]
cherry-pickup-ii
[ Python ] βœ… Simple Python Solution βœ…βœ… βœ…100% Optimal Solution
vaibhav0077
0
23
cherry pickup ii
1,463
0.701
Hard
21,824
https://leetcode.com/problems/cherry-pickup-ii/discuss/2218746/Memoization-and-bottom-up-both-3D-DP-easy-approach
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: # 3-D DP # dp Approach # Bottom-Up r=len(grid) c=len(grid[0]) dp=[[[0 for _ in range(c)] for _ in range(c)] for _ in range(r)] for i in range(r): for j1 in range(c): for j2 in range(c): if i==r-1 and j1==j2: dp[i][j1][j2]=grid[i][j1] elif(i==r-1): dp[i][j1][j2]=grid[i][j1]+grid[i][j2] for i in range(r-2,-1,-1): for j1 in range(c): for j2 in range(c): maxi=-float('inf') for dj1 in range(-1,2): for dj2 in range(-1,2): if j1==j2: value=grid[i][j1] else: value=grid[i][j1]+grid[i][j2] if j1+dj1>=0 and j1+dj1<c and j2+dj2>=0 and j2+dj2<c: value+=dp[i+1][j1+dj1][j2+dj2] else: value=-float('inf') maxi=max(maxi,value) dp[i][j1][j2]=maxi return dp[0][0][c-1] # Memoization r=len(grid) c=len(grid[0]) def solve(i,j1,j2): dp=[[[-1 for _ in range(c)] for _ in range(c)] for _ in range(r)] if j1<0 or j1>=c or j2<0 or j2>=c: return -float('inf') if i==r-1: if j1==j2: return grid[i][j1] else: return grid[i][j1]+grid[i][j2] maxi=-float('inf') if dp[i][j1][j2]!=-1: return dp[i][j1][j2] for dj1 in range(-1,2): for dj2 in range(-1,2): if j1==j2: maxi=max(maxi,grid[i][j1]+solve(i+1,j1+dj1,j2+dj2)) else: maxi=max(maxi,grid[i][j1]+grid[i][j2]+solve(i+1,j1+dj1,j2+dj2)) dp[i][j1][j2]=maxi return dp[i][j1][j2] return solve(0,0,c-1)
cherry-pickup-ii
Memoization and bottom-up both , 3D DP , easy-approach
Aniket_liar07
0
23
cherry pickup ii
1,463
0.701
Hard
21,825
https://leetcode.com/problems/cherry-pickup-ii/discuss/2112250/python-3-oror-bottom-up-dp-oror-O(m*n2)O(m*n2)
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dp = [[[0] * (n + 1) for _ in range(n + 1)] for _ in range(m)] for j1 in range(n): for j2 in range(n): dp[m - 1][j1][j2] = grid[m - 1][j1] + (grid[m - 1][j2] if j1 != j2 else 0) for i in range(m - 2, -1, -1): for j1 in range(n): for j2 in range(n): val = grid[i][j1] + (grid[i][j2] if j1 != j2 else 0) dp[i][j1][j2] = val + max(dp[i + 1][j1 - 1][j2 - 1], dp[i + 1][j1 - 1][j2], dp[i + 1][j1 - 1][j2 + 1], dp[i + 1][j1][j2 - 1], dp[i + 1][j1][j2], dp[i + 1][j1][j2 + 1], dp[i + 1][j1 + 1][j2 - 1], dp[i + 1][j1 + 1][j2], dp[i + 1][j1 + 1][j2 + 1]) return dp[0][0][n - 1]
cherry-pickup-ii
python 3 || bottom up dp || O(m*n^2)/O(m*n^2)
dereky4
0
41
cherry pickup ii
1,463
0.701
Hard
21,826
https://leetcode.com/problems/cherry-pickup-ii/discuss/2076503/Python-Iterative-Solution-O(M*N2)-Easy-To-Understand
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: N = len(grid) M = len(grid[0]) dp = [[[-1 for _ in range(M)] for _ in range(M)] for _ in range(N)] #Generate 3D Array directions = (-1, 0, 1) #Place beginning value dp[0][0][M-1] = grid[0][0] + grid[0][M-1] for row in range(N-1): for c1 in range(M): for c2 in range(M): if dp[row][c1][c2] == -1 : continue for x in directions: for y in directions: new_c1 = c1 + x new_c2 = c2 + y #Optimization (new_c1 < new_c2): As there is no reason for them to be in the same square since they would always lose value being on same square #You don't need to consider any paths that cross because those will already be considered. E.G robot 1 and robot 2 would essentially swap if(new_c1 < new_c2 and 0 <= new_c1 and new_c1 < M and 0 <= new_c2 and new_c2 < M): dp[row + 1][new_c1][new_c2] = max(dp[row + 1][new_c1][new_c2], dp[row][c1][c2] + grid[row+1][new_c1] + grid[row+1][new_c2]) #Need to check if a path with greater value was already found return max([dp[N-1][x][y] for x in range(M) for y in range(M)])
cherry-pickup-ii
[Python] Iterative Solution - O(M*N^2) - Easy To Understand
alexerling
0
21
cherry pickup ii
1,463
0.701
Hard
21,827
https://leetcode.com/problems/cherry-pickup-ii/discuss/1678353/Python-3-or-DFS-or-Intuitive-or-Easy
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: n,m=len(grid),len(grid[0]) rob1,rob2=(0,0),(0,m-1) direction=[(1,-1),(1,0),(1,1)] @lru_cache(maxsize=None) def traversal(r1,r2): if r1[0]==n-1: if 0<=r1[1]<m and 0<=r2[1]<m: maxC1,maxC2=grid[r1[0]][r1[1]],grid[r2[0]][r2[1]] elif 0<=r1[1]<m: maxC1,maxC2=grid[r1[0]][r1[1]],0 else: maxC1,maxC2=0,grid[r2[0]][r2[1]] return maxC1,maxC2 maxCherry1,maxCherry2=0,0 maxC=0 for r,c in direction: newrob1=(r1[0]+r,r1[1]+c) if 0<=newrob1[1]<m: cherry2=0 for row,col in direction: newrob2=(r2[0]+row,r2[1]+col) if 0<=newrob2[1]<m and newrob1!=newrob2: cher1,cher2=traversal(newrob1,newrob2) if maxC<cher1+cher2: maxC=cher1+cher2 maxCherry1=cher1 maxCherry2=cher2 maxCherry1=maxCherry1+grid[r1[0]][r1[1]] maxCherry2=maxCherry2+grid[r2[0]][r2[1]] return maxCherry1,maxCherry2 cherries1,cherries2=traversal(rob1,rob2) return cherries1+cherries2
cherry-pickup-ii
Python 3 | DFS | Intuitive | Easy
saa_73
0
34
cherry pickup ii
1,463
0.701
Hard
21,828
https://leetcode.com/problems/cherry-pickup-ii/discuss/1674650/Python-DP-beats-99.54
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) # cherrys[r1][r2] = max number of cherrys possible when robot1, robot2 end up in r1, r2 cell respectively on current row cherrys = [[0]*n for _ in range(n)] # starts with the first row cherrys[0][n-1] = grid[0][0] + grid[0][n-1] # move on to the next row from the previous row for i in range(1, m): nextCherrys = [[0]*n for _ in range(n)] # robot1 is always on the left. If robot2 is on the same cell or on the left of robot1, there must be a way # that they can swap the path without losing any cherry for r1 in range(n-1): for r2 in range(r1+1, n): # deal with edgecase when r1 = 0 or r2 = n-1 r1_pre = [r1-1, r1, r1+1] if r1 else [r1, r1+1] r2_pre = [r2-1, r2, r2+1] if r2 < n-1 else [r2-1, r2] # deal with inaccessible cells. # the maximum index r1 can reach on row i is i (moving to the right every row) # similarly the minimum index r2 can reach on row i is n-1-i (moving to the left every row) if r1 > i or r2 < n - 1 - i: nextCherrys[r1][r2] = 0 continue # the max number of cherrys on row i with robot1 in r1 and robot2 in r2 is the # max value of all possible (x, y) combinations that can reach (r1, r2) plus the cherrys in r1, r2 cells on row i nextCherrys[r1][r2] = max(cherrys[x][y] for x in r1_pre for y in r2_pre) + grid[i][r1] + grid[i][r2] cherrys = nextCherrys return max(cherrys[x][y] for x in range(n-1) for y in range(x+1, n))
cherry-pickup-ii
Python DP beats 99.54%
lurk369
0
21
cherry pickup ii
1,463
0.701
Hard
21,829
https://leetcode.com/problems/cherry-pickup-ii/discuss/1674143/Python-3-or-Dynamic-Programming-or-Beginner-or-Explained
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: def getAdj(robot1, x, y, n, m): if x == 1: if robot1 and y < 2: return [0] elif not robot1 and y > m-3: return [ m-1 ] else: return [] coords = list() if y >= 1: coords.append( y-1 ) if y < m-1: coords.append( y+1) coords.append( y) return coords n = len(grid) m = len(grid[0]) mem = [[[0 for k in range(m)] for j in range(m)] for i in range(n)] for j in range(m): for k in range(m): if k != j: mem[n-1][j][k] = grid[n-1][j]+grid[n-1][k] else: mem[n-1][j][k] = grid[n-1][j] for i in range(n-1,0,-1): for j in range(0, m): for k in range(0, m): adjRobot1 = getAdj(True, i,j, n, m) adjRobot2 = getAdj(False, i,k, n, m) for y1 in adjRobot1: for y2 in adjRobot2: if y1!=y2: mem[i-1][y1][y2] = max(mem[i-1][y1][y2], grid[i-1][y1]+grid[i-1][y2]+mem[i][j][k]) else: mem[i-1][y1][y2] = max(mem[i-1][y1][y2], grid[i-1][y1]+mem[i][j][k]) return mem[0][0][m-1]
cherry-pickup-ii
Python 3 | Dynamic Programming | Beginner | Explained
letyrodri
0
39
cherry pickup ii
1,463
0.701
Hard
21,830
https://leetcode.com/problems/cherry-pickup-ii/discuss/1674011/Python3-Easy-DFS-%2B-Memoization
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) @cache def dfs(i, j1, j2): # Invalid state, return 0 cherries if (i >= n or j1 < 0 or j1 >= m or j2 < 0 or j2 >= m): return 0 # Try all possible pairs of moves for j1 and j2 max_cherries = max(dfs(i + 1, j1 + k, j2 + l) for k in range(-1, 2) for l in range(-1, 2)) # Return total, if j1 = j2 exclude double count return grid[i][j1] + max_cherries + grid[i][j2] * int(j1 != j2) return dfs(0, 0, m - 1)
cherry-pickup-ii
Python3 - Easy DFS + Memoization βœ…
Bruception
0
105
cherry pickup ii
1,463
0.701
Hard
21,831
https://leetcode.com/problems/cherry-pickup-ii/discuss/977771/Iterative-Bottom-up-Solution-using-DP
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: cols = len(grid[0]) lastCol = cols-1 def getPositionsToValues(row: List[int]) -> List[List[int]]: return [[row[i] if i==j else row[i]+row[j] for j in range(0, cols)] for i in range(0, cols)] nextIndices = [range(max(0, index-1), min(lastCol, index+1)+1) for index in range(0, cols)] def getPrevMax(prevVals: List[List[int]], a: int, b: int) -> int: return max(prevVals[i][j] for i in nextIndices[a] for j in nextIndices[b]) currRowIndex = len(grid)-1 currRow = grid[currRowIndex] prevLevel = getPositionsToValues(currRow) while currRowIndex > 0: currRowIndex -= 1 currRow = grid[currRowIndex] currentLevel = getPositionsToValues(currRow) for i in range(0, cols): for j in range(0, cols): currentLevel[i][j] += getPrevMax(prevLevel, i, j) prevLevel = currentLevel return currentLevel[0][lastCol]
cherry-pickup-ii
Iterative Bottom-up Solution using DP
ShayBuchnik
0
71
cherry pickup ii
1,463
0.701
Hard
21,832
https://leetcode.com/problems/cherry-pickup-ii/discuss/1586666/Recursive-DFS-Solution-or-Time%3A-O(N2)-or-Space%3A-O(Height-of-the-Grid)
class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) @cache def dfs(row1, col1, row2, col2, n, m): if (col1 >= m or col1 < 0) or (col2 >= m or col2 < 0) or row1 >= n or row2 >= n: return -math.inf temp = grid[row1][col1] if row1 == row2 and col1 == col2 else grid[row1][col1] + grid[row2][col2] # if reached the bottom of the grid then return the temp value if row1 == n-1 and row2 == n-1: return temp return temp + max(dfs(row1+1, a, row2+1, b, n, m) for a in [col1-1, col1, col1+1] for b in [col2-1, col2, col2+1]) # one starting point is (0,0) and other is (0,m-1) return dfs(0, 0, 0, m-1, n, m)
cherry-pickup-ii
Recursive DFS Solution | Time: O(N^2) | Space: O(Height of the Grid)
pandeymanan024
-2
91
cherry pickup ii
1,463
0.701
Hard
21,833
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1975858/Python-3-greater-Using-heap
class Solution: def maxProduct(self, nums: List[int]) -> int: # approach 1: find 2 max numbers in 2 loops. T = O(n). S = O(1) # approach 2: sort and then get the last 2 max elements. T = O(n lg n). S = O(1) # approach 3: build min heap of size 2. T = O(n lg n). S = O(1) # python gives only min heap feature. heaq.heappush(list, item). heapq.heappop(list) heap = [-1] for num in nums: if num > heap[0]: if len(heap) == 2: heapq.heappop(heap) heapq.heappush(heap, num) return (heap[0]-1) * (heap[1]-1)
maximum-product-of-two-elements-in-an-array
Python 3 -> Using heap
mybuddy29
3
195
maximum product of two elements in an array
1,464
0.794
Easy
21,834
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/662754/Python-Built-in-sort-method-(100-speed-100-mem)
class Solution(object): def maxProduct(self, nums): nums.sort() return (nums[-1] -1) * (nums[-2]-1) """ :type nums: List[int] :rtype: int """
maximum-product-of-two-elements-in-an-array
[Python] Built-in sort method (100 % speed, 100 % mem)
drblessing
2
665
maximum product of two elements in an array
1,464
0.794
Easy
21,835
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2233960/Very-Very-Easy-Solution-oror-52ms-Faster-Than-95-oror-Python
class Solution: def maxProduct(self, nums: List[int]) -> int: x = max(nums) nums.remove(x) y = max(nums) return (x - 1) * (y - 1)
maximum-product-of-two-elements-in-an-array
Very, Very Easy Solution || 52ms, Faster Than 95 % || Python
cool-huip
1
95
maximum product of two elements in an array
1,464
0.794
Easy
21,836
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1683444/Python-O(n)-time-and-O(1)-space-by-finding-largest-two-numbers
class Solution: def maxProduct(self, nums: List[int]) -> int: max1 = float("-inf") max2 = float("-inf") for i in nums: if i > max1: max2 = max1 max1 = i elif i > max2: max2 = i return (max2-1) * (max1 -1)
maximum-product-of-two-elements-in-an-array
Python O(n) time and O(1) space by finding largest two numbers
snagsbybalin
1
44
maximum product of two elements in an array
1,464
0.794
Easy
21,837
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1357231/Easy-Python-Solution(98.84)
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[-1]-1)*(nums[-2]-1)
maximum-product-of-two-elements-in-an-array
Easy Python Solution(98.84%)
Sneh17029
1
245
maximum product of two elements in an array
1,464
0.794
Easy
21,838
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1159294/Python-Easiest-Solution
class Solution: def maxProduct(self, nums: List[int]) -> int: x = max(nums) #find 1st largest nums.remove(x) y = max(nums) #find 2nd largest return (x-1)*(y-1)
maximum-product-of-two-elements-in-an-array
Python Easiest Solution
aishwaryanathanii
1
80
maximum product of two elements in an array
1,464
0.794
Easy
21,839
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1150117/Python3-A-Single-Line-Solution
class Solution: def maxProduct(self, nums: List[int]) -> int: return((nums.pop(nums.index(max(nums))) - 1) * (nums.pop(nums.index(max(nums))) - 1))
maximum-product-of-two-elements-in-an-array
[Python3] A Single Line Solution
Lolopola
1
42
maximum product of two elements in an array
1,464
0.794
Easy
21,840
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1134842/Easy-Python-Solution-%3A-One-line
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort(reverse = True) return(nums[0]-1)*(nums[1]-1)
maximum-product-of-two-elements-in-an-array
Easy Python Solution : One line
YashashriShiral
1
79
maximum product of two elements in an array
1,464
0.794
Easy
21,841
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1045011/Python3-Simple-and-Easy-solution
class Solution: def maxProduct(self, nums: List[int]) -> int: nums = sorted(nums) return ((nums[-1]-1) * (nums[-2]-1))
maximum-product-of-two-elements-in-an-array
[Python3] Simple and Easy solution
vatsalbhuva11
1
96
maximum product of two elements in an array
1,464
0.794
Easy
21,842
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/971753/Python-Simple-Soution
class Solution: def maxProduct(self, nums: List[int]) -> int: m1=max(nums) nums.remove(m1) m2=max(nums) return (m1-1)*(m2-1)
maximum-product-of-two-elements-in-an-array
Python Simple Soution
lokeshsenthilkumar
1
180
maximum product of two elements in an array
1,464
0.794
Easy
21,843
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/716158/Python-or-Easy-Understandable-or-5-Lines-of-code
class Solution: def maxProduct(self, nums: List[int]) -> int: nums = sorted(nums) if len(nums) >= 2: return (nums[len(nums)-1]-1) * (nums[len(nums)-2]-1)
maximum-product-of-two-elements-in-an-array
Python | Easy Understandable | 5 Lines of code
omkv
1
124
maximum product of two elements in an array
1,464
0.794
Easy
21,844
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2849260/Python
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() a = nums[-1]-1 b = nums[-2]-1 return a * b
maximum-product-of-two-elements-in-an-array
Python
khanismail_1
0
1
maximum product of two elements in an array
1,464
0.794
Easy
21,845
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2845063/Python3-Solution-memory-beats-99-with-explanation
class Solution: def maxProduct(self, nums: List[int]) -> int: return (nums.pop(nums.index(max(nums))) - 1) * (max(nums) - 1)
maximum-product-of-two-elements-in-an-array
Python3 Solution - memory beats 99% - with explanation
sipi09
0
1
maximum product of two elements in an array
1,464
0.794
Easy
21,846
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2841161/Python-or-Simple-sorting-solution
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[-1] - 1)*(nums[-2] - 1)
maximum-product-of-two-elements-in-an-array
Python | Simple sorting solution
LordVader1
0
1
maximum product of two elements in an array
1,464
0.794
Easy
21,847
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2790951/python3-simple-sort-soln-2-lines
class Solution: def maxProduct(self, nums): sorted_num = sorted(nums) return (sorted_num[-1]-1)*(sorted_num[-2]-1)
maximum-product-of-two-elements-in-an-array
python3-simple sort soln-2 lines
alamwasim29
0
3
maximum product of two elements in an array
1,464
0.794
Easy
21,848
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2757865/python-2-lines-code
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[-1]-1)*(nums[-2]-1)
maximum-product-of-two-elements-in-an-array
python 2 lines code
Raghunath_Reddy
0
4
maximum product of two elements in an array
1,464
0.794
Easy
21,849
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2750631/one-line-solution
class Solution: def maxProduct(self, nums: List[int]) -> int: return (sorted(nums)[-1]-1 )*(sorted(nums)[-2]-1)
maximum-product-of-two-elements-in-an-array
one line solution
user6046z
0
2
maximum product of two elements in an array
1,464
0.794
Easy
21,850
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2729728/easy-way
class Solution: def maxProduct(self, nums: List[int]) -> int: l=sorted(nums) m=len(nums) return (l[m-2]-1)*(l[m-1]-1)
maximum-product-of-two-elements-in-an-array
easy way
sindhu_300
0
2
maximum product of two elements in an array
1,464
0.794
Easy
21,851
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2720769/Python-solution-without-any-inbuilt-function
class Solution: def maxProduct(self, nums: List[int]) -> int: largest_num = float('-inf') second_num = float('-inf') for num in nums: if largest_num <= num: second_num = largest_num largest_num = num if num < largest_num and num > second_num: second_num = num return (largest_num-1)*(second_num - 1)
maximum-product-of-two-elements-in-an-array
Python solution without any inbuilt function
danishs
0
7
maximum product of two elements in an array
1,464
0.794
Easy
21,852
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2667689/Python3-solution.-Clean-code-with-full-comments.-97.56-faster.
class Solution: def maxProduct(self, nums: List[int]) -> int: # Set two variables for the max and the second max values of the list with the negative infinite value. max_1 = float('-inf') max_2 = float('-inf') for i in range(len(nums)): # Find the max value. if max_1 <= nums[i]: # But also save the previous max value as the second max value. max_2 = max_1 max_1 = nums[i] # Now, saving the the former max value is not enough, we need to check if the # current nums[i] is bigger or equal to the current second max value, and smaller # or equal to the current max value. elif (max_2 <= nums[i]) and (nums[i] <= max_1): # If so, then overwrite the current second max value with the current nums[i] max_2 = nums[i] return (max_1 - 1) * (max_2 - 1) # Runtime: 50 ms, faster than 97.56% of Python3 online submissions for # Maximum Product of Two Elements in an Array. # Memory Usage: 13.9 MB, less than 48.12% of Python3 online submissions # for Maximum Product of Two Elements in an Array. # If you like my work, then I'll appreciate a like. Thanks!
maximum-product-of-two-elements-in-an-array
Python3 solution. Clean code with full comments. 97.56% faster.
375d
0
21
maximum product of two elements in an array
1,464
0.794
Easy
21,853
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2662802/Python-Easy-multiple-Solutions-with-and-without-Built-in-functions
class Solution(object): def maxProduct(self, nums): nums.sort(reverse=True) return((nums[0]-1)*(nums[1]-1))
maximum-product-of-two-elements-in-an-array
Python Easy multiple Solutions with and without Built in functions
shandilayasujay
0
9
maximum product of two elements in an array
1,464
0.794
Easy
21,854
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2662802/Python-Easy-multiple-Solutions-with-and-without-Built-in-functions
class Solution(object): def maxProduct(self, nums): first,second=0,0 for n in nums: if n >first: first,second=n,first else: second=max(second,n) return((first-1)*(second-1))
maximum-product-of-two-elements-in-an-array
Python Easy multiple Solutions with and without Built in functions
shandilayasujay
0
9
maximum product of two elements in an array
1,464
0.794
Easy
21,855
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2568935/EASY-PYTHON3-SOLUTION
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[-1]-1)*(nums[-2]-1)
maximum-product-of-two-elements-in-an-array
βœ…βœ” EASY PYTHON3 SOLUTION βœ…βœ”
rajukommula
0
47
maximum product of two elements in an array
1,464
0.794
Easy
21,856
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2541541/Python-One-Line-solution
class Solution: def maxProduct(self, nums: List[int]) -> int: nums1.sort(reverse=True) return (nums[1]-1)*(nums[0]-1)
maximum-product-of-two-elements-in-an-array
Python One Line solution
betaal
0
66
maximum product of two elements in an array
1,464
0.794
Easy
21,857
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2489051/Python-simple-solution-oror-beats-99
class Solution: def maxProduct(self, nums: List[int]) -> int: max_ele = [float("-inf"),float("-inf")] for ele in nums: if ele > max_ele[0]: temp = max_ele[0] max_ele[0] = ele max_ele[1] = temp elif ele > max_ele[1]: max_ele[1] = ele return (max_ele[0]-1)*(max_ele[1]-1)
maximum-product-of-two-elements-in-an-array
Python simple solution || beats 99%
aruj900
0
46
maximum product of two elements in an array
1,464
0.794
Easy
21,858
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2429877/python
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[len(nums)-1] - 1) * (nums[len(nums)-2] - 1)
maximum-product-of-two-elements-in-an-array
python
akashp2001
0
23
maximum product of two elements in an array
1,464
0.794
Easy
21,859
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2407672/Python-solution-with-no-for-loops
class Solution: def maxProduct(self, nums: List[int]) -> int: sorted_nums = sorted(nums) max_prod = (sorted_nums[-1] - 1) * (sorted_nums[-2] - 1) return max_prod
maximum-product-of-two-elements-in-an-array
Python solution with no for loops
samanehghafouri
0
13
maximum product of two elements in an array
1,464
0.794
Easy
21,860
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2390314/Python-simple-solution-or-max-numbers-or-O(n)
class Solution: def maxProduct(self, nums: List[int]) -> int: # mx1 - max element, mx2 - second max element mx1 = nums[0] if nums[0] > nums[1] else nums[1] mx2 = nums[1] if nums[0] > nums[1] else nums[0] for num in nums[2:]: if num > mx1: mx1, mx2 = num, mx1 elif num > mx2: mx2 = num return (mx1 - 1) * (mx2 - 1)
maximum-product-of-two-elements-in-an-array
Python simple solution | max numbers | O(n)
wilspi
0
29
maximum product of two elements in an array
1,464
0.794
Easy
21,861
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2161329/Simple-Logic-in-python
class Solution: def maxProduct(self, nums: List[int]) -> int: max_num = heapq.nlargest(2,nums) return (max_num[0]-1)*(max_num[1]-1)
maximum-product-of-two-elements-in-an-array
Simple Logic in python
writemeom
0
63
maximum product of two elements in an array
1,464
0.794
Easy
21,862
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2159561/Python-or-O(N)-solution-or-Neat-and-clean-code
class Solution: def maxProduct(self, nums: List[int]) -> int: max1 = 0 max2 = 0 for num in nums: if num > max1: max2 = max1 max1 = num elif num > max2: max2 = num return (max1 - 1) * (max2 - 1)
maximum-product-of-two-elements-in-an-array
Python | O(N) solution | Neat and clean code
__Asrar
0
28
maximum product of two elements in an array
1,464
0.794
Easy
21,863
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2154423/Python-Two-solutions
class Solution: def maxProduct(self, nums: List[int]) -> int: # Time: O(N) [heappop is constant] # Taking 1st largest and 2nd largest nums = [-num for num in nums] heapq.heapify(nums) first = heapq.heappop(nums) second = heapq.heappop(nums) return (abs(first) - 1) * (abs(second) - 1) # Time: O(N) max1 = max(nums) nums.remove(max1) max2 = max(nums) return (max1-1) * (max2-1)
maximum-product-of-two-elements-in-an-array
[Python] Two solutions
Gp05
0
27
maximum product of two elements in an array
1,464
0.794
Easy
21,864
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2047599/Python-simple-oneliner
class Solution: def maxProduct(self, nums: List[int]) -> int: return (sorted(nums)[-1]-1)*(sorted(nums)[-2]-1)
maximum-product-of-two-elements-in-an-array
Python simple oneliner
StikS32
0
51
maximum product of two elements in an array
1,464
0.794
Easy
21,865
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/2008528/50-ms-Beginner-Friendly-Python-Solution
class Solution: import copy def maxProduct(self, nums: List[int]) -> int: temp = copy.copy(nums) fh = max(nums) nums.remove(fh) sh = max(nums) nums.remove(sh) return ((fh-1)*(sh-1))
maximum-product-of-two-elements-in-an-array
50 ms Beginner Friendly Python Solution
itsmeparag14
0
38
maximum product of two elements in an array
1,464
0.794
Easy
21,866
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1988236/Python-Easiest-Solution-With-Explanation-or-Sorting-or-Beg-to-adv-or
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() # sort the list to get the highest values in the list and to have a maximum value after the product, according to the logic given in the problem statement itself. return (nums[-1] - 1) * (nums[-2] -1) # took 2 highest values there in the array, to have a maximum value after performing product again as per the given condition in the problem statement.
maximum-product-of-two-elements-in-an-array
Python Easiest Solution With Explanation | Sorting | Beg to adv |
rlakshay14
0
46
maximum product of two elements in an array
1,464
0.794
Easy
21,867
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1906173/Python-Solutions-or-Two-Ways-or-O(n*log(n))-O(n)-or-Both-over-90-Faster
class Solution: def maxProduct(self, nums: List[int]) -> int: # n * logn nums.sort() return (nums[-1]-1) * (nums[-2]-1) # n largest = max(nums) nums.remove(largest) secLargest = max(nums) return (largest - 1) * (secLargest - 1)
maximum-product-of-two-elements-in-an-array
Python Solutions | Two Ways | O(n*log(n)) / O(n) | Both over 90% Faster
Gautam_ProMax
0
53
maximum product of two elements in an array
1,464
0.794
Easy
21,868
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1885945/Python3-Easy-solution
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[-1]-1)*(nums[-2]-1)
maximum-product-of-two-elements-in-an-array
Python3 Easy solution
czariwnl
0
33
maximum product of two elements in an array
1,464
0.794
Easy
21,869
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1884182/Python-solution-with-memory-usage-less-than-99
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort(reverse=True) return (nums[0]-1) * (nums[1]-1)
maximum-product-of-two-elements-in-an-array
Python solution with memory usage less than 99%
alishak1999
0
23
maximum product of two elements in an array
1,464
0.794
Easy
21,870
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1862069/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def maxProduct(self, nums: List[int]) -> int: a = max(nums) nums.remove(a) b = max(nums) ans = (a-1)*(b-1) return ans
maximum-product-of-two-elements-in-an-array
Python (Simple Approach and Beginner-Friendly)
vishvavariya
0
17
maximum product of two elements in an array
1,464
0.794
Easy
21,871
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1831137/2-Lines-Python-Solution-oror-60-Faster-oror-Memory-less-than-95
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[-1]-1)*(nums[-2]-1)
maximum-product-of-two-elements-in-an-array
2-Lines Python Solution || 60% Faster || Memory less than 95%
Taha-C
0
24
maximum product of two elements in an array
1,464
0.794
Easy
21,872
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1672990/In-Python-TC-O(N)-and-Space-O(1)
class Solution: def maxProduct(self, l: List[int]) -> int: f2=-1 if l[0]>l[1]: f1 = l[0] index = 0 else: f1=l[1] index = 1 for i in range(len(l)): if l[i]>f1: f2=f1 f1=l[i] index = i if l[i]>f2 and f1>=l[i] and index!=i: f2=l[i] return (f1-1)*(f2-1)
maximum-product-of-two-elements-in-an-array
In Python TC - O(N) & Space - O(1)
gamitejpratapsingh998
0
49
maximum product of two elements in an array
1,464
0.794
Easy
21,873
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1590675/Python-3-faster-than-95-O(n)-time-O(1)-space
class Solution: def maxProduct(self, nums: List[int]) -> int: max1 = max2 = -math.inf for num in nums: if num >= max1: max1, max2 = num, max1 elif num > max2: max2 = num return (max1 - 1) * (max2 - 1)
maximum-product-of-two-elements-in-an-array
Python 3 faster than 95%, O(n) time, O(1) space
dereky4
0
230
maximum product of two elements in an array
1,464
0.794
Easy
21,874
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1416201/Python-Faster-than-100-in-One-Line
class Solution(object): def maxProduct(self, nums): return (nums.pop(nums.index(max(nums)))-1) * (max(nums)-1)
maximum-product-of-two-elements-in-an-array
Python Faster than 100% in One Line
MyNameIsCorn
0
124
maximum product of two elements in an array
1,464
0.794
Easy
21,875
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1394880/Python3-Faster-than-97-of-the-Solutions
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[-1]-1)*(nums[-2]-1)
maximum-product-of-two-elements-in-an-array
Python3 - Faster than 97% of the Solutions
harshitgupta323
0
58
maximum product of two elements in an array
1,464
0.794
Easy
21,876
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1391076/Python3-Heap-Solve_How-to-use-python-list-%22nums%22-globally
class Solution: def maxProduct(self, nums: List[int]) -> int: def mx_heapify(heap, sz, i): # print(heap) nonlocal nums, heap_sz # print(nums) l = 2*i + 1 r = 2*i + 2 # print(i,l, r) if l <= heap_sz-1 and nums[l] >= nums[i]: largest = l else: largest = i if r <= heap_sz-1 and nums[r] > nums[largest]: largest = r # print(largest, i) if largest != i: nums[largest], nums[i] = nums[i], nums[largest] mx_heapify(nums, heap_sz, largest) def build_max_heap(heap, heap_sz): nonlocal nums for i in range((heap_sz//2)-1, -1, -1): mx_heapify(nums, heap_sz, i) heap_sz = len(nums) build_max_heap(nums, heap_sz) # print(nums) def mx_return(heap, sz): nonlocal nums, heap_sz # print(nums[heap_sz-1]) mx = nums[0] # print(mx) nums[0] = nums[heap_sz-1] heap_sz -= 1 mx_heapify(nums,heap_sz,0) return mx x1 = mx_return(nums,heap_sz) x2 = mx_return(nums, heap_sz) return (x1-1)*(x2-1)
maximum-product-of-two-elements-in-an-array
Python3- Heap Solve_How to use python list "nums" globally
mint412
0
63
maximum product of two elements in an array
1,464
0.794
Easy
21,877
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1331339/Python-3-%3A-EASY-solution-using-heapq-3-lines
class Solution: def maxProduct(self, nums: List[int]) -> int: heapq.heapify(nums) a = heapq.nlargest(2,nums) return (a[0]-1)*(a[1]-1)
maximum-product-of-two-elements-in-an-array
Python 3 : EASY , solution using heapq , 3 lines
rohitkhairnar
0
197
maximum product of two elements in an array
1,464
0.794
Easy
21,878
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1296444/Easy-Solutionoror-Python
class Solution: def maxProduct(self, nums: List[int]) -> int: heapq.heapify(nums) final=heapq.nlargest(2,nums) return (final[0]-1)*(final[1]-1)
maximum-product-of-two-elements-in-an-array
Easy Solution|| Python
stdeshmukh
0
38
maximum product of two elements in an array
1,464
0.794
Easy
21,879
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1161582/Python-fast-and-pythonic
class Solution: def maxProduct(self, nums: List[int]) -> int: first, second = nums[0], nums[1] for i in nums[2:]: first, second = sorted([first, second, i])[1:] return (first-1)*(second-1)
maximum-product-of-two-elements-in-an-array
[Python] fast and pythonic
cruim
0
68
maximum product of two elements in an array
1,464
0.794
Easy
21,880
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1128094/Simple-2-lines-Solution-in-Python-Faster-than-96
class Solution: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[len(nums)-1] - 1)*(nums[len(nums)-2] - 1)
maximum-product-of-two-elements-in-an-array
Simple 2 lines Solution in Python; Faster than 96%
Annushams
0
200
maximum product of two elements in an array
1,464
0.794
Easy
21,881
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2227297/Python-easy-solution
class Solution: def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int: hc.sort() vc.sort() maxh = hc[0] maxv = vc[0] for i in range(1, len(hc)): maxh = max(maxh, hc[i] - hc[i-1]) maxh = max(maxh, h - hc[-1]) for i in range(1, len(vc)): maxv = max(maxv, vc[i] - vc[i-1]) maxv = max(maxv, w - vc[-1]) return maxh*maxv % (10**9 + 7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python easy solution
lokeshsenthilkumar
3
81
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,882
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2226091/Python-3-Solution-with-comments
class Solution: def getMaxConsecutiveDifference(self,distances,lenTotal): #Appending first boundary distances.append(0) #Appending last boundary distances.append(lenTotal) #Sorting distances.sort() maxDistancesDiff = 0 #Looping to calculate max consecutive distance for i in range(1,len(distances)): #Getting the difference of two consecutive elements currDiff = distances[i] - distances[i-1] #Updating max difference value maxDistancesDiff = max(maxDistancesDiff,currDiff) return maxDistancesDiff def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: #Getting max consecutive distance from horizontal distance horizontalMaxDiff = self.getMaxConsecutiveDifference(horizontalCuts,h) #Getting max consecutive distance from vertical distance verticalMaxDiff = self.getMaxConsecutiveDifference(verticalCuts,w) #Returning the result after performing the modulo operation return ((horizontalMaxDiff*verticalMaxDiff)%(10**9+7))
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python 3 Solution with comments
manojkumarmanusai
2
131
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,883
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2225470/Python-oror-Explanation-oror-Fast
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: maxH,maxW=-1,-1 horizontalCuts.sort() hc=[0]+horizontalCuts+[h] verticalCuts.sort() vc=[0]+verticalCuts+[w] nH=len(hc) for i in range(1,nH): maxH=max(maxH ,hc[i]-hc[i-1] ) nw=len(vc) for i in range(1,nw): maxW=max(maxW ,vc[i]-vc[i-1] ) return (maxH*maxW % (10**9 + 7))
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python || Explanation || Fast
palashbajpai214
2
73
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,884
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1717171/Python3-EASY-2-lines-with-visual-examples
class Solution: def getMaxSpace(self, cuts: List[int], end: int) -> int: maxSpace = max(cuts[0], end-cuts[-1]) for i in range(1,len(cuts)): maxSpace = max(maxSpace, cuts[i] - cuts[i-1]) return maxSpace def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: return self.getMaxSpace(sorted(horizontalCuts), h) * self.getMaxSpace(sorted(verticalCuts), w) % (10**9+7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python3 EASY 2 lines with visual examples
lifetrees
2
229
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,885
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1609711/Python-or-O(nlogn)-or-Simple-Solution
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: horizontalCuts = [0] + horizontalCuts + [h] verticalCuts = [0] + verticalCuts + [w] horizontalCuts.sort() verticalCuts.sort() horizontal_max = -1 vertical_max = -1 for index in range(1, len(horizontalCuts)): horizontal_max = max(horizontal_max, horizontalCuts[index]-horizontalCuts[index-1]) for index in range(1, len(verticalCuts)): vertical_max = max(vertical_max, verticalCuts[index]-verticalCuts[index-1]) return (horizontal_max * vertical_max) % ((10**9)+7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python | O(nlogn) | Simple Solution
Call-Me-AJ
2
245
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,886
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2227944/Simple-Python-Solution-oror-Easy-to-understand
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: horizontalCuts.sort(reverse=True) verticalCuts.sort(reverse=True) hcMaxDiff = max(h - horizontalCuts[0], horizontalCuts[-1]) vcMaxDiff = max(w - verticalCuts[0], verticalCuts[-1]) for i in range(len(horizontalCuts)-1): diff = horizontalCuts[i] - horizontalCuts[i+1] if (diff > hcMaxDiff) : hcMaxDiff = diff for i in range(len(verticalCuts)-1): diff = verticalCuts[i] - verticalCuts[i+1] if diff > vcMaxDiff: vcMaxDiff = diff return (vcMaxDiff * hcMaxDiff) % 1000000007
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Simple Python Solution || Easy to understand
rprakash01
1
22
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,887
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2227884/Python-easy-solution-or-95-faster
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: horizontalCuts.sort() verticalCuts.sort() horizontalCuts = [0] + horizontalCuts + [h] verticalCuts = [0] + verticalCuts + [w] max_w, max_h = 0, 0 for i in range(1, len(verticalCuts)): current_h = verticalCuts[i] - verticalCuts[i - 1] if max_h < current_h: max_h = current_h for i in range(1, len(horizontalCuts)): current_w = horizontalCuts[i] - horizontalCuts[i - 1] if max_w < current_w: max_w = current_w return (max_w * max_h) % ((10 ** 9) + 7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python easy solution | 95% faster
prameshbajra
1
57
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,888
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2226358/Python-oror-Sorting
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: horizontalCuts.sort() verticalCuts.sort() v_maximum = 0 h_maximum = 0 for j in range(len(verticalCuts)+ 1): if j == 0: vertical_value = verticalCuts[0] elif j == len(verticalCuts): vertical_value = w - verticalCuts[j-1] else: vertical_value = verticalCuts[j] - verticalCuts[j-1] v_maximum = max(v_maximum, vertical_value) for i in range(len(horizontalCuts)+1): if i == 0: horizontal_value = horizontalCuts[0] elif i == len(horizontalCuts): horizontal_value = h - horizontalCuts[i-1] else: horizontal_value = horizontalCuts[i] - horizontalCuts[i-1] h_maximum = max(h_maximum, horizontal_value) return (v_maximum * h_maximum) % 1000000007
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python || Sorting
narasimharaomeda
1
10
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,889
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2225355/Python-3-Easy-solution-with-explaination
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: mh,mv = 0,0 hori,verti = sorted(horizontalCuts),sorted(verticalCuts) #getting sorted arrays with easy names if len(hori)==1: mh = max(hori[0],h-hori[0]) #Since there is only 1 cut so take max value from both ends of the cake else: mh = max(hori[0],h-hori[-1]) # difference from the edges from both the cuts at both ends for i in range(1,len(hori)): mh = max(mh,hori[i]-hori[i-1]) # to get max difference between consecutive cuts if len(verti)==1: mv = max(verti[0],w-verti[0]) # same as horizintal else: mv = max(verti[0],w-verti[-1]) for i in range(1,len(verti)): mv = max(mv,verti[i]-verti[i-1]) return (mh*mv)%1000000007
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python 3 Easy solution with explaination
Akash3502
1
42
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,890
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2225239/python3-or-explained-or-easy-to-understand-or-basic-or-sort
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: # adding lower and upper limit to horizontalCuts horizontalCuts.append(0) horizontalCuts.append(h) # adding lower and upper limit to verticalCuts verticalCuts.append(0) verticalCuts.append(w) verticalCuts.sort() horizontalCuts.sort() mx_h = self.find_max_diff(verticalCuts) # max diff in horizontalCuts mx_v = self.find_max_diff(horizontalCuts) # max diff in verticalCuts return (mx_h*mx_v)%(10**9+7) # to find the maximum difference btw elements in array def find_max_diff(self, arr): max_d = 0 p = arr[0] for e in arr[1:]: max_d = max(max_d, e-p) p = e return max_d
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
python3 | explained | easy to understand | basic | sort
H-R-S
1
47
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,891
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1248789/simplest-solution
class Solution: def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int: hc.append(0) hc.append(h) hc.sort() vc.append(0) vc.append(w) vc.sort() ans1=0 for i in range(1,len(hc)): ans1=max(ans1,hc[i]-hc[i-1]) ans2=0 for j in range(1,len(vc)): ans2=max(ans2,vc[j]-vc[j-1]) return ans1*ans2%1000000007
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
simplest solution
_kumarmohit_
1
118
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,892
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1216926/Python3-O(nlgn)-concise-solution
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: dx = dy = 0 horizontalCuts = [0] + sorted(horizontalCuts) + [h] verticalCuts = [0] + sorted(verticalCuts) + [w] for precut, cut in zip(horizontalCuts, horizontalCuts[1:]): dx = max(dx, cut - precut) for precut, cut in zip(verticalCuts, verticalCuts[1:]): dy = max(dy, cut - precut) return (dx * dy) % (10 ** 9 + 7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python3 O(nlgn) concise solution
savikx
1
110
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,893
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2828095/Python-sorting
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: horizontalCuts.sort() verticalCuts.sort() hh = [] prev = 0 maxH = float('-inf') for n in horizontalCuts + [h]: maxH = max(maxH, n - prev) prev = n vh = [] prev = 0 maxW = float('-inf') for n in verticalCuts + [w]: maxW = max(maxW, n - prev) prev = n return maxH * maxW % (10 ** 9 + 7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python, sorting
swepln
0
1
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,894
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2428954/Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts-oror-Python3
class Solution: def maxArea(self, h: int, w: int, horizontal_cuts: List[int], vertical_cuts: List[int]) -> int: horizontal_cuts.sort() vertical_cuts.sort() max_horizontal_cut = horizontal_cuts[0] for i in range(1, len(horizontal_cuts)): max_horizontal_cut = max(max_horizontal_cut, horizontal_cuts[i] - horizontal_cuts[i-1]) max_horizontal_cut = max(max_horizontal_cut, h - horizontal_cuts[-1]) max_vertical_cut = vertical_cuts[0] for i in range(1, len(vertical_cuts)): max_vertical_cut = max(max_vertical_cut, vertical_cuts[i] - vertical_cuts[i-1]) max_vertical_cut = max(max_vertical_cut, w - vertical_cuts[-1]) return (max_horizontal_cut * max_vertical_cut) % (10**9 + 7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts || Python3
vanshika_2507
0
57
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,895
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2241398/oror-PYTHON-oror-EXPLAINED-oror-EASY
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: horizontalCuts.extend([0,h]); verticalCuts.extend([0,w]); horizontalCuts.sort(reverse=True); verticalCuts.sort(reverse=True); hans=[] vans=[] for i in range(len(horizontalCuts)-1): hans.append(horizontalCuts[i]-horizontalCuts[i+1]) for i in range(len(verticalCuts)-1): vans.append(verticalCuts[i]-verticalCuts[i+1]) return (max(hans)*max(vans))%((10**9)+7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
|| PYTHON || EXPLAINED || EASY
Tiwari_ji07
0
55
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,896
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2228788/Fast-Non-Redundant-Python-Code
class Solution: def max_cutdist(self, bound, cuts) : cuts.append(0) cuts.append(bound) cuts.sort() max_dist = 0 for cut_idx in range(len(cuts)- 1) : max_dist = max(max_dist, cuts[cut_idx+1] - cuts[cut_idx]) return max_dist def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: max_hdist = self.max_cutdist(h, horizontalCuts) max_vdist = self.max_cutdist(w, verticalCuts) return max_hdist*max_vdist %(10**9+7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Fast, Non-Redundant Python Code
RobbyRivenbark
0
5
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,897
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2228518/Python-simple-solution
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: # Insert and append the first and last postion horizontalCuts.insert(0,0) horizontalCuts.append(h) verticalCuts.insert(0,0) verticalCuts.append(w) # get the length lh = len(horizontalCuts) lv = len(verticalCuts) # sort the arrays to find the difference horizontalCuts.sort() verticalCuts.sort() # check for the horizontal difference between the cuts max_dif_h = 0 for i in range(1,lh): dif_h = (horizontalCuts[i] - horizontalCuts[i-1]) max_dif_h = max(dif_h,max_dif_h) # check for the horizontal difference between the cuts max_dif_v = 0 for i in range(1,lv): dif_v = (verticalCuts[i] - verticalCuts[i-1]) max_dif_v = max(dif_v,max_dif_v) # return return (max_dif_h * max_dif_v) % (10**9 + 7)
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python simple solution
sudoberlin
0
6
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,898
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2228418/Python-or-Commented-or-Greedy-or-O(nlogn)
# Greedy Solution # Time: O(nlogn + nlogn + n + n), Sorting both lists + iterations through two input Lists. # Space: O(1), Constant space used (excluding size of input lists). class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: maxHorizontalSlice, maxVerticalSlice = 0, 0 # Variables to hold max slice sizes. horizontalCuts.extend([0, h]) # Extends lists with "cuts" at ends of cake. verticalCuts.extend([0, w]) horizontalCuts.sort() # Sorts list to allow for iteration through. verticalCuts.sort() for i in range(1, len(horizontalCuts)): # Iterate through horizontal cuts. sliceSize = horizontalCuts[i] - horizontalCuts[i-1] # Gets current slice size. maxHorizontalcut = max(maxHorizontalSlice, sliceSize) # Gets max slice size. for i in range(1, len(verticalCuts)): # Iterate through vertical cuts. sliceSize = verticalCuts[i] - verticalCuts[i-1] # Gets current slice size. maxVerticalSlice = max(maxVerticalSlice, sliceSize) # Gets max slice size. return (maxHorizontalSlice * maxVerticalSlice) % (10**9 + 7) # Return max slice area % (10^9 + 7).
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
Python | Commented | Greedy | O(nlogn)
bensmith0
0
11
maximum area of a piece of cake after horizontal and vertical cuts
1,465
0.409
Medium
21,899