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/reverse-words-in-a-string/discuss/1046044/Python-%2B-Stack-Easy-to-understand. | class Solution:
def reverseWords(self, s: str) -> str:
s = s + " " # extra spacing for indicating end of a string
stack = []
word = ""
i = 0
while i < len(s):
if s[i] == " ":
stack.append(word)
word = ""
elif s[i] != " ":
word += s[i]
i += 1
new = ""
while stack:
eachWord = stack.pop()
if eachWord:
new = new + " " + eachWord
return new[1:] | reverse-words-in-a-string | [Python + Stack] Easy to understand. | rohanmathur91 | 2 | 332 | reverse words in a string | 151 | 0.318 | Medium | 2,300 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/737151/PythonPython3-Reverse-Words-in-a-String | class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(s.split()[::-1]) | reverse-words-in-a-string | [Python/Python3] Reverse Words in a String | newborncoder | 2 | 937 | reverse words in a string | 151 | 0.318 | Medium | 2,301 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812518/One-line-and-clean | class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.strip().split())) | reverse-words-in-a-string | One line and clean | nilesh507 | 1 | 8 | reverse words in a string | 151 | 0.318 | Medium | 2,302 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812481/Python-solution | class Solution:
def reverseWords(self, s: str) -> str:
lists = s.split(" ")[::-1]
newlists = [x for x in lists if x != '']
return " ".join(newlists) | reverse-words-in-a-string | Python solution | maomao1010 | 1 | 16 | reverse words in a string | 151 | 0.318 | Medium | 2,303 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811741/Pyhon-1-Line-solution | class Solution:
def reverseWords(self, s: str) -> str:
# x[::-1] for x in s.split() returns a list where each word is reversed
# " ".join generates a string of above, concatenated with spaces
# finally we return reverse of above step ie [::-1]
return " ".join(x[::-1] for x in s.split())[::-1] | reverse-words-in-a-string | Pyhon 1 Line solution | dryice | 1 | 7 | reverse words in a string | 151 | 0.318 | Medium | 2,304 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811730/One-Line-Solution-Using-Python-3 | class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.split())) | reverse-words-in-a-string | One Line Solution Using Python 3 | sadman_s | 1 | 7 | reverse words in a string | 151 | 0.318 | Medium | 2,305 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2809951/in-N-time-cmplexity | class Solution:
def reverseWords(self, s: str) -> str:
arr=s.split()
arr.reverse()
return(" ".join(arr)) | reverse-words-in-a-string | in N time cmplexity | droj | 1 | 3 | reverse words in a string | 151 | 0.318 | Medium | 2,306 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2520873/Python3-easiest-possible-Solution-No-inbuilt-Function | class Solution:
def reverseWords(self, S: str) -> str:
s = []
temp = ''
for i in (S + ' '):
if i == ' ':
if temp != '':
s.append(temp)
temp = ''
else:
temp += i
return " ".join(s[::-1]) | reverse-words-in-a-string | Python3 easiest possible Solution No inbuilt Function | pranjalmishra334 | 1 | 107 | reverse words in a string | 151 | 0.318 | Medium | 2,307 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2393958/Python3-solution-99.99-space-optimised-(with-explanation) | class Solution:
def reverseWords(self, s: str) -> str:
t, res = "",[]
# add one space to end of s so that we can extract all words
s += " "
i = 0
while i < len(s):
ele = s[i]
if ele != " ":
# if the character is not a space, keep adding characters
t += ele
i += 1
else:
# being here means that we just got our first word stored in t
# store the word in a list - res
# empty the string t for storing further words
res.append(t)
t = ""
# if we have continued spaces after the first space then increment i
while i < len(s)-1 and s[i+1] == " ":
i += 1
i+=1
# if first word in res is a space it would mean that we had many spaces at
# the start of the string s
# eg -- "___hello world" -> when we encounter first space
# we go in else: of above loop and add one "" and then increment i for the
# remaining spaces; hence one space remains.
if res[0] == "":
res = res[1:]
return " ".join(res[::-1])
# return the strings joined in reversed list res | reverse-words-in-a-string | Python3 solution 99.99% space optimised (with explanation) | jinwooo | 1 | 86 | reverse words in a string | 151 | 0.318 | Medium | 2,308 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/1983033/Python-3-Clean-Solution-using-String-Splitting | class Solution:
def reverseWords(self, s: str) -> str:
words = s.split(' ')
words = [word for word in words if word != ""]
return " ".join(words[-1::-1]) | reverse-words-in-a-string | [Python 3] Clean Solution using String Splitting | hari19041 | 1 | 137 | reverse words in a string | 151 | 0.318 | Medium | 2,309 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/1863794/1-Line-Python-Solution-oror-92-Faster-oror-Memory-less-than-99 | class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join([w for w in s.split(' ') if w!=''][::-1]) | reverse-words-in-a-string | 1-Line Python Solution || 92% Faster || Memory less than 99% | Taha-C | 1 | 104 | reverse words in a string | 151 | 0.318 | Medium | 2,310 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/1161974/Python3-solution-one-liner | class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(s.split()[::-1]) | reverse-words-in-a-string | Python3 solution one-liner | adarsh__kn | 1 | 54 | reverse words in a string | 151 | 0.318 | Medium | 2,311 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/1125395/One-line-python-solution | class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(s.split()[::-1]) | reverse-words-in-a-string | One line python solution | harshitkd | 1 | 141 | reverse words in a string | 151 | 0.318 | Medium | 2,312 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2833787/Brute-Force-Solution | class Solution:
def reverseWords(self, s: str) -> str:
# l , r = 0 , len(s)-1
# while l <= r:
# if s[l] != "":
# if s[r] != "":
# begin , end = 0 , begin+1
# while begin:
# if s[begin] != ""
# # while s[::-1]
words = s.split()
res = ""
for i in list(reversed(words)):
res += i
res+=" "
# res+=" "
return res.strip() | reverse-words-in-a-string | Brute Force Solution | DevinMartin | 0 | 3 | reverse words in a string | 151 | 0.318 | Medium | 2,313 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2831845/Python-Solution-Stack-oror-String-oror-Explained | class Solution:
def reverseWords(self, s: str) -> str:
new=""
l=[]
for i in s:
if i!=" ": #if not empty space then put it in new
new=new+i
else: #if space found then put all characters of new in l as a single element in l
if len(new)!=0:
l.append(new)
new=""
if len(new)!=0: #append if characters remaining in new
l.append(new)
l=l[::-1] #reverse
ans=""
for i in l:
ans=ans+i+" " #join the string present in l
return ans[:len(ans)-1] #removing the back space present in ans | reverse-words-in-a-string | Python Solution - Stack || String || Explained✔ | T1n1_B0x1 | 0 | 4 | reverse words in a string | 151 | 0.318 | Medium | 2,314 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2827982/Easy-One-Liner-Python-Solution | class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(s.split()[::-1]) | reverse-words-in-a-string | Easy One Liner Python Solution | jagdtri2003 | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,315 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2826545/Python-Two-Liner | class Solution:
def reverseWords(self, s: str) -> str:
res = s.strip().split()[::-1]
return " ".join(res) | reverse-words-in-a-string | Python Two-Liner | nitin_ed | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,316 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2823955/Python-1-line-code | class Solution:
def reverseWords(self, s: str) -> str:
return (' '.join(((s.strip()).split())[::-1])).strip() | reverse-words-in-a-string | Python 1 line code | kumar_anand05 | 0 | 3 | reverse words in a string | 151 | 0.318 | Medium | 2,317 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2818342/Simple-Python-solution | class Solution:
def reverseWords(self, s: str) -> str:
l = s.strip().split()
l = l[::-1]
return ' '.join(l) | reverse-words-in-a-string | Simple Python solution | TDMxNoob | 0 | 3 | reverse words in a string | 151 | 0.318 | Medium | 2,318 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812812/O(n)-Simple-Solution-using-Python | class Solution:
def reverseWords(self, s: str) -> str:
l= s.split(" ")
l.reverse()
ll=[]
for i in l:
if i:
ll.append(i)
return " ".join(ll) | reverse-words-in-a-string | O(n) Simple Solution using Python | Ratna3445 | 0 | 4 | reverse words in a string | 151 | 0.318 | Medium | 2,319 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812345/Python-easy-and-concise | class Solution(object):
def reverseWords(self, s):
l=s.split()
s=" ".join(l[::-1])
return s | reverse-words-in-a-string | Python-easy and concise | singhdiljot2001 | 0 | 2 | reverse words in a string | 151 | 0.318 | Medium | 2,320 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812300/Python3-easy-solution | class Solution:
def reverseWords(self, s: str) -> str:
s_l = s.strip().split()
res = []
for i in range(len(s_l)-1, -1, -1):
res.append(s_l[i])
return " ".join(res) | reverse-words-in-a-string | Python3 easy solution | dcnorman | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,321 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812276/Python-or-O(N) | class Solution:
def reverseWords(self, s: str) -> str:
word, result = "", ""
space, empty = " ", ""
N = len(s)
for i in range(N-1,-1,-1):
char = s[i]
if not char == space:
word = char + word
elif word:
if result: result += space
result += word
word = empty
if word:
if result: result += space
result += word
return result | reverse-words-in-a-string | Python | O(N) | k1729g | 0 | 3 | reverse words in a string | 151 | 0.318 | Medium | 2,322 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812206/Easy-in-Python | class Solution:
def reverseWords(self, s: str) -> str:
l1 = [k for k in s.split(" ") if k != ""]
return " ".join(l1[::-1]) | reverse-words-in-a-string | Easy in Python | DNST | 0 | 2 | reverse words in a string | 151 | 0.318 | Medium | 2,323 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812197/Python3-solution | class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(s.split()[::-1]) | reverse-words-in-a-string | Python3 solution | avs-abhishek123 | 0 | 3 | reverse words in a string | 151 | 0.318 | Medium | 2,324 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812148/Very-easy-python3-solution | class Solution:
def reverseWords(self, s: str) -> str:
s = s.split()
print(s)
stack = []
for i in range(len(s)-1, -1, -1):
stack.append(s[i])
return ' '.join(stack) | reverse-words-in-a-string | Very easy python3 solution | farzanamou | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,325 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812104/Python3-oror-One-Line-oror-Faster-than-92 | class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(s.split()[::-1]) | reverse-words-in-a-string | ✅ Python3 || One Line || Faster than 92% | PabloVE2001 | 0 | 5 | reverse words in a string | 151 | 0.318 | Medium | 2,326 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2812048/Python-No-in-built-function-used | class Solution:
def reverseWords(self, s: str) -> str:
result = ''
tmp = ''
noDoubleSpace = False
for c in s:
if c != ' ':
tmp = tmp + c
noDoubleSpace = True
elif c == ' ' and noDoubleSpace:
result = ' ' + tmp + result
tmp = ''
noDoubleSpace = False
if tmp:
result = tmp + result
else:
result = result[1:]
return result | reverse-words-in-a-string | Python, No in-built function used | Boss-08 | 0 | 2 | reverse words in a string | 151 | 0.318 | Medium | 2,327 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811922/Daily-LeetCoding-Challenge-November-Day-13-(Python3-fastest-solution) | class Solution:
def reverseWords(self, s: str) -> str:
a=s.split()
b=[a[i] for i in range(-1,-len(a)-1,-1)]
return " ".join(b) | reverse-words-in-a-string | 🗓️ Daily LeetCoding Challenge November, Day 13 (Python3 fastest solution) | Jishnu_69 | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,328 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811843/Python-3-Line-Solution | class Solution:
def reverseWords(self, s: str) -> str:
words = s.split()
reverse_words = words[::-1]
return ' '.join(reverse_words) | reverse-words-in-a-string | Python - 3 Line Solution | theleastinterestingman | 0 | 4 | reverse words in a string | 151 | 0.318 | Medium | 2,329 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811817/Python-Simple-Solution | class Solution:
def reverseWords(self, s: str) -> str:
r = s.split()
r.reverse()
return ' '.join(r) | reverse-words-in-a-string | Python Simple Solution | chrihop | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,330 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811806/Simple-Single-line-Solution | class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(s.strip().split()[::-1]) | reverse-words-in-a-string | Simple Single line Solution | babuamar455 | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,331 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811757/96-time-easy-to-understand | class Solution:
def reverseWords(self, s: str) -> str:
x1 = s.split()
res = s.split()
x1_r = len(x1)-1
for i in range(len(x1)):
res[i] = x1[x1_r]
x1_r -= 1
return " ".join(res) | reverse-words-in-a-string | 96% time, easy to understand | Exxidate | 0 | 2 | reverse words in a string | 151 | 0.318 | Medium | 2,332 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811744/Python-2-Line-Solution | class Solution:
def reverseWords(self, s: str) -> str:
a=(list(s.split()))[::-1]
return " ".join(a) | reverse-words-in-a-string | ✔️ [ Python ] 🐍🐍2 Line Solution✅✅ | sourav638 | 0 | 3 | reverse words in a string | 151 | 0.318 | Medium | 2,333 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811696/Python-Solution | class Solution:
def reverseWords(self, s: str) -> str:
stack=[]
s=s.strip()
strlist = s.split()
for word in strlist:
stack.append(word)
out=""
while stack:
k = stack.pop()
out+=k+" "
return out.rstrip() | reverse-words-in-a-string | Python Solution | dineshrajan | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,334 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811564/python-3-line-solution | class Solution:
def reverseWords(self, s: str) -> str:
s = s.split(' ')
s = s[::-1]
return ' '.join(c for c in s if c != '') | reverse-words-in-a-string | python 3-line solution | justinjia0201 | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,335 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811563/Easy-and-straight-forward | class Solution:
def reverseWords(self, s: str) -> str:
return self.main(s)
def wordSplitter(self,s):
res = []
stack = []
for i in range(0,len(s)):
if s[i]!=" ":
stack.append(s[i])
elif s[i]==" ":
res.append(self.stackToWord(stack))
stack = []
res.append(self.stackToWord(stack))
return self.listFilter(res)
def listFilter(self, lst):
temp = []
for i in lst:
if i:
temp.append(i)
return temp
def stackToWord(self, stack):
word = ""
for i in stack:
word += i
return word
def reverser(self, lst):
stack = []
for i in lst:
stack.append(i)
lst = []
while stack:
lst.append(stack.pop())
return lst
def listToString(self, lst):
string = ""
for i in lst:
string += " " + i
return string[1:]
def main(self,s):
return self.listToString(self.reverser(self.wordSplitter(s))) | reverse-words-in-a-string | Easy and straight forward | tanaydwivedi095 | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,336 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811539/Easy-python-solution. | class Solution:
def reverseWords(self, s: str) -> str:
s = s.lstrip()
s = s.rstrip()
res = []
temp = ''
for ch in s:
if ch == ' ' and not temp:
continue
if ch == ' ' and temp:
res.append(temp)
res.append(ch)
temp = ''
else:
temp += ch
res.append(temp)
return ''.join(res[::-1]) | reverse-words-in-a-string | Easy python solution. | i-haque | 0 | 3 | reverse words in a string | 151 | 0.318 | Medium | 2,337 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811537/Easy-python-solution. | class Solution:
def reverseWords(self, s: str) -> str:
s = s.lstrip()
s = s.rstrip()
res = []
temp = ''
for ch in s:
if ch == ' ' and not temp:
continue
if ch == ' ' and temp:
res.append(temp)
res.append(ch)
temp = ''
else:
temp += ch
res.append(temp)
return ''.join(res[::-1]) | reverse-words-in-a-string | Easy python solution. | i-haque | 0 | 2 | reverse words in a string | 151 | 0.318 | Medium | 2,338 |
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2811484/Easy-Python-SolutionororSlicing | class Solution:
def reverseWords(self, s: str) -> str:
s=s.split()
a=s[::-1]
return(' '.join(a)) | reverse-words-in-a-string | Easy Python Solution||Slicing | ankitr8055 | 0 | 1 | reverse words in a string | 151 | 0.318 | Medium | 2,339 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1608907/Python3-DYNAMIC-PROGRAMMING-Explained | class Solution:
def maxProduct(self, nums: List[int]) -> int:
curMax, curMin = 1, 1
res = nums[0]
for n in nums:
vals = (n, n * curMax, n * curMin)
curMax, curMin = max(vals), min(vals)
res = max(res, curMax)
return res | maximum-product-subarray | ✔️[Python3] DYNAMIC PROGRAMMING, Explained | artod | 90 | 9,700 | maximum product subarray | 152 | 0.349 | Medium | 2,340 |
https://leetcode.com/problems/maximum-product-subarray/discuss/384555/Python-Solution-(DP) | class Solution:
def maxProduct(self, nums: List[int]) -> int:
if not nums:
return 0
if len(nums) == 1:
return nums[0]
min_so_far, max_so_far, max_global = nums[0], nums[0], nums[0]
for i in range(1, len(nums)):
max_so_far, min_so_far = max(min_so_far*nums[i], max_so_far*nums[i], nums[i]), min(min_so_far*nums[i], max_so_far*nums[i], nums[i])
max_global = max(max_global, max_so_far)
return max_global | maximum-product-subarray | Python Solution (DP) | FFurus | 13 | 1,700 | maximum product subarray | 152 | 0.349 | Medium | 2,341 |
https://leetcode.com/problems/maximum-product-subarray/discuss/841169/Python-3-or-DP-or-Explanations | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans, cur_max, cur_min = -sys.maxsize, 0, 0
for num in nums:
if num > 0: cur_max, cur_min = max(num, num*cur_max), min(num, num*cur_min)
else: cur_max, cur_min = max(num, num*cur_min), min(num, num*cur_max)
ans = max(ans, cur_max)
return ans if ans else max(nums) | maximum-product-subarray | Python 3 | DP | Explanations | idontknoooo | 10 | 1,600 | maximum product subarray | 152 | 0.349 | Medium | 2,342 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1681214/Python-Intuitive-O(n)-time-explained | class Solution:
def maxProduct(self, nums: List[int]) -> int:
totalMax = prevMax = prevMin = nums[0]
for i,num in enumerate(nums[1:]):
currentMin = min(num, prevMax*num, prevMin*num)
currentMax = max(num, prevMax*num, prevMin*num)
totalMax = max(currentMax, totalMax)
prevMax = currentMax
prevMin = currentMin
return totalMax | maximum-product-subarray | Python Intuitive O(n) time, explained | kenanR | 6 | 476 | maximum product subarray | 152 | 0.349 | Medium | 2,343 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1337502/Python-3-O(n)-Solution-Hints-with-Spoiler | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans , max_p, min_p = nums[0], 1, 1
for num in nums:
max_p, min_p = max(num, min_p * num, max_p * num), min(num, min_p * num, max_p * num)
ans = max(ans, max_p)
return ans | maximum-product-subarray | [Python 3] O(n) Solution Hints with Spoiler | wasi0013 | 6 | 490 | maximum product subarray | 152 | 0.349 | Medium | 2,344 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1037018/Python3-Concise-Memoization | class Solution:
def maxProduct(self, nums: List[int]) -> int:
self.memo = {}
def dfs(i, currentProduct):
key = (i, currentProduct)
if (key in self.memo):
return self.memo[key]
if (i >= len(nums)):
return currentProduct
# 3 choices, Include the current number in the product, start a new product, or end the product
ans = max(dfs(i + 1, currentProduct * nums[i]), dfs(i + 1, nums[i]), currentProduct)
self.memo[key] = ans
return ans
return dfs(1, nums[0]) | maximum-product-subarray | Python3 - Concise Memoization | Bruception | 4 | 438 | maximum product subarray | 152 | 0.349 | Medium | 2,345 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2510789/Python-Beats-99-Accurate-Solution-oror-Documented | class Solution:
def maxProduct(self, nums: List[int]) -> int:
minProd = maxProd = result = nums[0] # minimum product, maximum product and result
for n in nums[1:]: # for each num
t = [n, minProd*n, maxProd*n] # temp array
minProd, maxProd = min(t), max(t) # update minProd and maxProd
result = max(result, minProd, maxProd) # update the result
return result | maximum-product-subarray | [Python] Beats 99% Accurate Solution || Documented | Buntynara | 3 | 201 | maximum product subarray | 152 | 0.349 | Medium | 2,346 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1657714/Python-Kadane-like-algorithm | class Solution:
def maxProduct(self, nums: List[int]) -> int:
result = nums[0]
max_ = min_ = 1
for n in nums:
max_, min_ = max(n, n * max_, n * min_), min(n, n * max_, n * min_)
result = max(result, max_)
return result | maximum-product-subarray | Python, Kadane-like algorithm | blue_sky5 | 3 | 198 | maximum product subarray | 152 | 0.349 | Medium | 2,347 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2058236/Simple-Python-Solution | class Solution:
def maxProduct(self, nums: List[int]) -> int:
pos = nums[0]
neg = nums[0]
best = nums[0]
for i in range(1,len(nums)):
prevMax = max(pos*nums[i],neg*nums[i],nums[i])
prevMin = min(pos*nums[i],neg*nums[i],nums[i])
pos = prevMax
neg = prevMin
best = max(prevMax,best)
return best | maximum-product-subarray | Simple Python Solution | Resocram | 2 | 85 | maximum product subarray | 152 | 0.349 | Medium | 2,348 |
https://leetcode.com/problems/maximum-product-subarray/discuss/695664/Python-DP-Bottom-Up-Solution | class Solution:
def maxProduct(self, nums: List[int]) -> int:
min_cache = [nums[0]]
max_cache = [nums[0]]
for i in range(1, len(nums)):
min_cache.append(min(min_cache[i - 1] * nums[i], nums[i], max_cache[i - 1] * nums[i]))
max_cache.append(max(max_cache[i - 1] * nums[i], nums[i], min_cache[i - 1] * nums[i]))
return max(min_cache + max_cache) | maximum-product-subarray | Python DP Bottom-Up Solution | bennyCache3000 | 2 | 269 | maximum product subarray | 152 | 0.349 | Medium | 2,349 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2406778/Python-3-oror-96-ms-faster-than-84.40-of-Python3 | class Solution:
def maxProduct(self, nums: List[int]) -> int:
curMax, curMin = 1, 1
res = max(nums)
for i in nums:
if i == 0:
curMax = curMin = 1
continue
temp = curMax*i
curMax = max(temp, curMin*i, i)
curMin = min(temp, curMin*i, i)
res = max(res, curMax)
return res | maximum-product-subarray | Python 3 || 96 ms, faster than 84.40% of Python3 | sagarhasan273 | 1 | 98 | maximum product subarray | 152 | 0.349 | Medium | 2,350 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2380481/Python-O(N)-oror-Simple-and-Beginner-friendly-solution | class Solution:
def maxProduct(self, nums: List[int]) -> int:
curmin, curmax = 1, 1
res = max(nums)
for i in nums:
if i == 0:
curmin, curmax = 1, 1
continue
temp = curmax * i
curmax = max(temp, curmin*i, i)
curmin = min(temp, curmin*i, i)
res = max(res, curmax)
return res | maximum-product-subarray | Python - O(N) || Simple and Beginner friendly solution | dayaniravi123 | 1 | 179 | maximum product subarray | 152 | 0.349 | Medium | 2,351 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2318607/O(N)-solution-or-C%2B%2B-or-Python-or-Easy-Solution | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans = nums[0]
maxi = ans
mini = ans
for i in range(1,len(nums)):
if(nums[i]<0):
maxi, mini = mini, maxi
maxi = max(nums[i], maxi*nums[i])
mini = min(nums[i], mini*nums[i])
ans = max(ans, maxi)
return ans | maximum-product-subarray | O(N) solution | C++ | Python | Easy Solution | arpit3043 | 1 | 217 | maximum product subarray | 152 | 0.349 | Medium | 2,352 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2283430/88-ms-faster-than-93.24-of-Python3-online-submissions-for-Maximum-Product-Subarray. | class Solution:
def maxProduct(self, nums: List[int]) -> int:
res = max(nums)
curMax, curMin = 1, 1
for n in nums:
if n == 0:
curMax, curMin = 1, 1
continue
tmp = curMax * n
curMax = max(tmp, curMin*n, n)
curMin = min(tmp, curMin*n, n)
res = max(res, curMax)
return res | maximum-product-subarray | 88 ms, faster than 93.24% of Python3 online submissions for Maximum Product Subarray. | sagarhasan273 | 1 | 106 | maximum product subarray | 152 | 0.349 | Medium | 2,353 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2219325/Python-Kadanes-oror-Extra-Space-approach-with-full-working-explanation | class Solution(object):
def maxProduct(self, A): # Time: O(n) and Space: O(n)
B = A[::-1]
for i in range(1, len(A)):
A[i] *= A[i - 1] or 1 # if A[i] * A[i-1] = 0, store A[i] = 1 rather than 0
B[i] *= B[i - 1] or 1
return max(A + B) # Combining the two array | maximum-product-subarray | Python [ Kadanes || Extra Space ] approach with full working explanation | DanishKhanbx | 1 | 125 | maximum product subarray | 152 | 0.349 | Medium | 2,354 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2219325/Python-Kadanes-oror-Extra-Space-approach-with-full-working-explanation | class Solution:
def maxProduct(self, nums: List[int]) -> int: # Time: O(n) and Space: O(1)
res = max(nums)
curMin, curMax = 1, 1
for n in nums:
if n == 0:
curMin, curMax = 1, 1
continue
temp = n * curMax
curMax = max(n * curMax, n * curMin, n)
curMin = min(temp, n * curMin, n)
res = max(res, curMax)
return res | maximum-product-subarray | Python [ Kadanes || Extra Space ] approach with full working explanation | DanishKhanbx | 1 | 125 | maximum product subarray | 152 | 0.349 | Medium | 2,355 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1676277/Python-%2253.-Maximum-Subarray%22-logic-Time%3A-O(n)-Space-O(1) | class Solution:
def maxProduct(self, nums: List[int]) -> int:
# Goal to find the largest at the end
# find the largest at ith
# Use "53. Maximum Subarray" concept
# However there are negative number, if there are two negative then it will be positive and might be the biggest.
# Therefore, use two variable to store the maximum and minimum, at ith number we will check the previous maximum and minimum times the current values and store the current max and current min
# Time: O(n) ,Space, O(1)
smallest = 1
largest = 1
res = -float(inf) # to record the maximum
for n in nums:
temp_small = smallest
smallest = min(n,n*smallest,n*largest)
largest = max(n,n*temp_small,n*largest)
res = max(res,largest)
return res | maximum-product-subarray | [Python] "53. Maximum Subarray" logic, Time: O(n) ,Space, O(1) | JackYeh17 | 1 | 143 | maximum product subarray | 152 | 0.349 | Medium | 2,356 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1581368/Divide-and-Conquer-better-than-98 | class Solution:
def subArrayProd(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
firstNegPos = -1
lastNegPos = -1
even = True
for i in range(len(nums)):
if nums[i] < 0:
lastNegPos = i
if firstNegPos == -1:
firstNegPos = i
even = not even
prod = 1
if even:
for n in nums:
prod *= n
else:
prod1 = 1
for i in range(lastNegPos):
prod1 *= nums[i]
prod2 = 1
for i in range(firstNegPos+1, len(nums)):
prod2 *= nums[i]
prod = max(prod1, prod2)
return prod
def maxProduct(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
zeroPositions = []
for i in range(len(nums)):
if nums[i] == 0:
zeroPositions.append(i)
if len(zeroPositions) == 0:
return self.subArrayProd(nums)
else:
prods = [0]
lastZero = -1
for z in zeroPositions:
if z == 0 or lastZero + 1 == z:
lastZero += 1
continue
if len(nums[lastZero+1:z]) > 0:
prods.append(self.subArrayProd(nums[lastZero+1:z]))
lastZero = z
if len(nums[z+1:]) > 0:
prods.append(self.subArrayProd(nums[z+1:]))
return max(prods) | maximum-product-subarray | Divide and Conquer better than 98% | ratnadeepb | 1 | 102 | maximum product subarray | 152 | 0.349 | Medium | 2,357 |
https://leetcode.com/problems/maximum-product-subarray/discuss/405396/Python-O(N)-time-O(1)-space-two-pass-solution-with-explination | class Solution:
def maxProduct(self, nums: List[int]) -> int:
all_vals = 1
non_negative = 1
maximum = 0
#first pass, look at all_vals and non_negative vals
for n in nums:
if n == 0:
all_vals = 1
non_negative = 1
elif n < 0:
all_vals *= n
non_negative = 1
maximum = max(maximum, all_vals)
else:
all_vals *= n
non_negative *= n
maximum = max(maximum, max(all_vals, non_negative))
#second pass, take all_vals, non_negative vals were already dealt with in pass 1
all_vals = 1
for n in nums[::-1]:
if n == 0:
all_vals = 1
else:
all_vals *= n
maximum = max(maximum, all_vals)
#if the maximum is still zero then take the max of the list
if maximum == 0:
return max(nums)
else:
return maximum | maximum-product-subarray | Python O(N) time O(1) space, two pass solution with explination | ElectricAvenue | 1 | 294 | maximum product subarray | 152 | 0.349 | Medium | 2,358 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2847229/Python-solution | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans = nums[0]
ma = ans
mi = ans
n = len(nums)
for i in range(1, n):
if nums[i] < 0:
ma, mi = mi, ma
ma = max(nums[i], ma*nums[i])
mi = min(nums[i], mi*nums[i])
ans = max(ma, ans)
return ans | maximum-product-subarray | Python solution | vivekpandey3999 | 0 | 2 | maximum product subarray | 152 | 0.349 | Medium | 2,359 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2834452/Greedy-like-Python-Solution.-Verbose-easy-to-understand. | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans = min(nums)
def update(x):
'''
Easy way to maintain global maximum
'''
nonlocal ans
if x> ans:
ans = x
def max_product_non_zero(arr):
total_prod = 1
for i in range(len(arr)):
total_prod *= arr[i]
if total_prod > 0 :
update(total_prod)
return
prod = 1
for i in range(len(arr)):
if arr[i] < 0:
if i!=0:
update(prod)
if i < len(arr)-1:
rem = total_prod / (prod * arr[i])
update(rem)
prod = prod * arr[i]
return
n = len(nums)
start = 0
for i in range(n):
if nums[i] == 0:
if i > 0 and i> start:
max_product_non_zero(nums[start: i])
update(0)
start = i + 1
if start >=n:
break
if start<n:
max_product_non_zero(nums[start:])
return int(ans) | maximum-product-subarray | Greedy like Python Solution. Verbose, easy to understand. | drauni | 0 | 7 | maximum product subarray | 152 | 0.349 | Medium | 2,360 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2820107/Python-3-Explained-O(N)-solution-faster-then-97.17 | class Solution:
# product of the array part
def getProduct(self, nums, start, end):
if start >= end:
return float('-inf')
product = 1
for i in range(start, end):
product *= nums[i]
return product
def maxProduct(self, nums: List[int]) -> int:
n = len(nums)
if n == 1:
return nums[0]
fst_neg_idx = -1
last_neg_idx = -1
last_zero_idx = -1
n_neg = 0
max_prod = float('-inf')
for i in range(n):
# count negative values statistics
if nums[i] < 0:
if fst_neg_idx == -1:
fst_neg_idx = i
last_neg_idx = i
n_neg += 1
# count max product of the array part between last and current zero values
elif nums[i] == 0:
if n_neg % 2 == 0:
max_prod = max(max_prod,
self.getProduct(nums, last_zero_idx+1, i))
else:
max_prod = max(max_prod,
self.getProduct(nums, fst_neg_idx+1, i),
self.getProduct(nums,
last_zero_idx+1,
last_neg_idx))
# don't forget about zero itself!
max_prod = max(max_prod, 0)
# reset negative values statistics
fst_neg_idx = -1
last_neg_idx = -1
n_neg = 0
last_zero_idx = i
# count max product of the last array part
if n_neg % 2 == 0:
max_prod = max(max_prod,
self.getProduct(nums, last_zero_idx+1, n))
else:
max_prod = max(max_prod,
self.getProduct(nums, fst_neg_idx+1, n),
self.getProduct(nums, last_zero_idx+1, last_neg_idx))
return max_prod | maximum-product-subarray | [Python 3] Explained O(N) solution, faster then 97.17% | LebedevaElena | 0 | 6 | maximum product subarray | 152 | 0.349 | Medium | 2,361 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2812008/Maximum-Product-Subarray-problem-solution-beats-99.87-(Python) | class Solution:
def maxProduct(self, nums: List[int]) -> int:
temp=1
ans=nums[0]
for i in range(len(nums)):
n=nums[i]
temp*=n
if(n>ans):
ans=n
if(temp>ans):
ans=temp
if(n==0):
temp=1
ans2=nums[len(nums)-1]
temp=1
for i in reversed(range(len(nums))):
n=nums[i]
temp*=n
if(n>ans2):
ans2=n
if(temp>ans2):
ans2=temp
if(n==0):
temp=1
return max(ans, ans2) | maximum-product-subarray | Maximum Product Subarray problem solution, beats 99.87% (Python) | than_kaou | 0 | 10 | maximum product subarray | 152 | 0.349 | Medium | 2,362 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2811494/faster-than-99-94 | class Solution:
def maxProduct(self, nums: List[int]) -> int:
l = 0
h = []
s = 0
t = min(nums)
m=min(nums)
for i in range(len(nums)):
if s==0 and nums[i]!=0:
s=1
if nums[i]==0:
h.append([l,i,s])
l=i+1
t=0
s*=nums[i]
h.append([l,len(nums),s])
print(h)
s1 = 1
s2 = 1
for i in h:
if i[2]>=0:
if m < i[2]:
m=max(m,i[2])
else:
k=i[0]
g=i[1]-1
while k < i[1]:
s1*=nums[k]
s2*=nums[g]
k+=1
g-=1
t=max(t,s1,s2)
if t>m:
m=t
s1=1
s2=1
return m | maximum-product-subarray | faster than 99-94% | hibit | 0 | 5 | maximum product subarray | 152 | 0.349 | Medium | 2,363 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2809887/Simple-short-python-code | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans,tempneg,temppos = -2*100000,1,1
for i in nums:
tempneg,temppos = min(i,i*tempneg,i*temppos),max(i,i*tempneg,i*temppos)
ans = max(ans,temppos)
return ans | maximum-product-subarray | Simple short python code | vIshal_kumar912 | 0 | 4 | maximum product subarray | 152 | 0.349 | Medium | 2,364 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2805341/Python-(Simple-Maths) | class Solution:
def maxProduct(self, nums):
cur_max, cur_min, res = 1, 1, nums[0]
for i in nums:
vals = (i,i*cur_min,i*cur_max)
cur_max, cur_min = max(vals), min(vals)
res = max(res,cur_max)
return res | maximum-product-subarray | Python (Simple Maths) | rnotappl | 0 | 4 | maximum product subarray | 152 | 0.349 | Medium | 2,365 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2766561/Dynamic-Programming-approach | class Solution:
def maxProduct(self, nums: List[int]) -> int:
Max = nums[0]
Min = nums[0]
ans = Max
# Calculate Max so far and Min so far
# 100*100 can be huge but
# also -100*-100 can be huge
for i in range(1, len(nums)):
curr = nums[i]
t = curr*Max
Max = max(curr, t, curr*Min) # since t = nums[i]*Max
Min = min(curr, t, curr*Min) # Max has changed, using t
ans = max(ans, Max)
return ans | maximum-product-subarray | Dynamic Programming approach | pratiklilhare | 0 | 9 | maximum product subarray | 152 | 0.349 | Medium | 2,366 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2726390/Python-fast-easy-Sol.-with-2-lines-of-explanation | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans=nums[0]
maxx,minn=ans,ans
for i in range(1,len(nums)):
# 1. Edge Case : Negative * Negative = Positive
# 2. So we need to keep track of minimum values also, as they can yield maximum values.
if nums[i]<0:
maxx,minn=minn,maxx
maxx=max(nums[i],maxx*nums[i])
minn=min(nums[i],minn*nums[i])
ans=max(ans,maxx)
return ans | maximum-product-subarray | Python fast easy Sol. with 2 lines of explanation | pranjalmishra334 | 0 | 24 | maximum product subarray | 152 | 0.349 | Medium | 2,367 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2660316/Python-Solution-explained-in-O(n)-time-94-Faster | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans = nums[0]
temp = 1
for num in nums:
temp *= num
ans = max(ans,temp)
if temp == 0:
temp = 1
temp = 1
for i in range(len(nums)-1,-1,-1):
temp *= nums[i]
ans = max(ans,temp)
if temp == 0:
temp = 1
return ans | maximum-product-subarray | ✅ [Python] Solution explained in O(n) time 94% Faster | dc_devesh7 | 0 | 120 | maximum product subarray | 152 | 0.349 | Medium | 2,368 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2630804/Simple-python-code-with-explanation | class Solution:
def maxProduct(self, nums: List[int]) -> int:
#create a variable(res) and store it's value as maximum of nums(list)
res = max(nums)
#create two variables current maximum and current minimum and assign their values as 1
currmax = 1
currmin = 1
#iterate over the elements in the list
for n in nums:
#if the element is 0
if n == 0:
#then set the current max and current min values to 1
currmax = 1
currmin = 1
continue
#before changing the currmax value store it in temp
temp = currmax * n
#current maximum will be the maximum of (currmax*n,currmin*n,n)
currmax = max(currmax *n , currmin*n,n)
#current minimum will be the minimum of (currmax*n,currmin*n,n)
currmin = min(temp, currmin*n,n)
#res value will be the maximum of current maximum and res
res = max(currmax,res)
#return the res after finishing for loop
return res | maximum-product-subarray | Simple python code with explanation | thomanani | 0 | 38 | maximum product subarray | 152 | 0.349 | Medium | 2,369 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2628356/O(N)-Time-Kadane's-2-pass-solution | class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
msf = -999999999999
prod = 1
zeroExists = False
for i in nums:
prod *= i
if(prod == 0):
prod = 1
zeroExists = True
continue
msf = max(msf, prod)
nums.reverse()
prod = 1
for i in nums:
prod *= i
if(prod == 0):
prod = 1
zeroExists = True
continue
msf = max(msf, prod)
if zeroExists:
return max(msf, 0)
return msf | maximum-product-subarray | O(N) Time Kadane's 2 pass solution | karanysingh | 0 | 83 | maximum product subarray | 152 | 0.349 | Medium | 2,370 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2507501/Python-DP-Solution | class Solution:
def maxProduct(self, nums: List[int]) -> int:
maxi = [nums[0]] * len(nums)
mini = [nums[0]] * len(nums)
mx = maxi[0]
for i in range(1, len(nums)):
maxi[i] = max(nums[i], maxi[i-1]*nums[i], mini[i-1]*nums[i])
mini[i] = min(nums[i], maxi[i-1]*nums[i], mini[i-1]*nums[i])
mx = max(maxi[i], mini[i], mx)
return mx | maximum-product-subarray | Python DP Solution | DietCoke777 | 0 | 118 | maximum product subarray | 152 | 0.349 | Medium | 2,371 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2233771/Python-Fastest%3A-Easy-to-Understand-O(N)-Solution. | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans = 0
currentProduct = 1
for ele in nums:
if(ele != 0):
currentProduct = currentProduct*ele
ans = max(ans, currentProduct)
else:
currentProduct = 1
currentProduct = 1
for i in range(len(nums)-1, -1, -1):
if(nums[i] != 0):
currentProduct = currentProduct*nums[i]
ans = max(ans, currentProduct)
else:
currentProduct = 1
return ans | maximum-product-subarray | Python Fastest: Easy to Understand O(N) Solution. | maharanasunil | 0 | 154 | maximum product subarray | 152 | 0.349 | Medium | 2,372 |
https://leetcode.com/problems/maximum-product-subarray/discuss/2193406/DP-Easy-approach-or-Python | class Solution:
def maxProduct(self, nums: List[int]) -> int:
maxSoFar = nums[0]
minSoFar = nums[0]
osum = nums[0]
for i in range(1,len(nums)):
temp = max(max(nums[i],maxSoFar * nums[i]), nums[i] * minSoFar)
minSoFar = min(min(nums[i],maxSoFar * nums[i]),nums[i]*minSoFar)
maxSoFar = temp
osum = max(maxSoFar,osum)
return osum | maximum-product-subarray | DP Easy approach | Python | bliqlegend | 0 | 129 | maximum product subarray | 152 | 0.349 | Medium | 2,373 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1933542/Python-Dynamic-Programming | class Solution:
def maxProduct(self, nums: List[int]) -> int:
res = max(nums)
curMax, curMin = 1, 1
for i in nums:
if i == 0:
curMax, curMin = 1, 1
temp = curMax * i
curMax = max(temp, curMin * i, i)
curMin = min(temp, curMin * i, i)
res = max(res, curMax)
return res | maximum-product-subarray | Python - Dynamic Programming | dayaniravi123 | 0 | 84 | maximum product subarray | 152 | 0.349 | Medium | 2,374 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1849570/fixed-kadanes-runtime-beats-97.97 | class Solution(object):
def maxProduct(self, nums):
if len(nums)==1:
return nums[0]
newnums=[[nums[0]]]
count=0
for i in nums[1:]:
if i == 0:
newnums.append([])
count+=1
else:
newnums[count].append(i)
while [] in newnums:
newnums.remove([])
maxProd=0
for s in newnums:
maxProd=max(maxProd,self.lazySplitedArray(s))
return maxProd
def lazySplitedArray(self,nums):
list=[]
l = len(nums)
for i in range(l):
if nums[i]<0:
list.append(i)
if len(list)%2==0:
for i in list:
nums[i]=nums[i]*-1
return self.kadanesFixed(nums)
else:
nums_1,nums_2=[0]*l,[0]*l
for i in range(l):
if i in list[1:]:
nums_1[i]=nums[i]*-1
else:
nums_1[i]=nums[i]
for i in range(l):
if i in list[:-1]:
nums_2[i]=nums[i]*-1
else:
nums_2[i]=nums[i]
return max(self.kadanesFixed(nums_1),self.kadanesFixed(nums_2))
def kadanesFixed(self,nums):
maxPrd=nums[0]
currPrd=1
for i in range(len(nums)):
currPrd*=nums[i]
maxPrd=max(maxPrd,currPrd)
currPrd=max(currPrd,1)
return maxPrd | maximum-product-subarray | fixed kadanes runtime beats 97.97 % | tranduchuy682 | 0 | 233 | maximum product subarray | 152 | 0.349 | Medium | 2,375 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1792313/O(n)-using-dictionary | class Solution:
def maxProduct(self, nums: List[int]) -> int:
d = {1:1}
product = 1
maxproduct = min(nums)
for i in nums:
product *= i
if i == 0:
product = 1
d = {1:1}
maxproduct = max(maxproduct, 0)
continue
for j in d.keys():
result = product/j
maxproduct = max(maxproduct, result)
d[product] = 1
return int(maxproduct) | maximum-product-subarray | O(n) - using dictionary | yuwei-1 | 0 | 142 | maximum product subarray | 152 | 0.349 | Medium | 2,376 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1779026/Oythin-easy-to-read-and-understand-or-DP | class Solution:
def maxProduct(self, nums: List[int]) -> int:
maxp, minp, ans = nums[0], nums[0], nums[0]
for i in range(1, len(nums)):
x = max(nums[i], maxp*nums[i], minp*nums[i])
y = min(nums[i], maxp*nums[i], minp*nums[i])
maxp, minp = x, y
ans = max(ans, maxp)
return ans | maximum-product-subarray | Oythin easy to read and understand | DP | sanial2001 | 0 | 171 | maximum product subarray | 152 | 0.349 | Medium | 2,377 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1768128/Python-or-Recursion-or-Memo | class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans=-inf
@lru_cache(None)
def dfs(i):
nonlocal ans
if i==len(nums)-1:
return nums[i],nums[i]#lo,hi
lo,hi=dfs(i+1)
n=nums[i]
ans=max(ans,lo,n,hi)
return min(lo*n,n,hi*n),max(lo*n,n,hi*n)
z=dfs(0)
return max(ans,z[1]) | maximum-product-subarray | Python | Recursion | Memo | heckt27 | 0 | 199 | maximum product subarray | 152 | 0.349 | Medium | 2,378 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1610159/Dynamic-Programming%3A-Record-Maximum-and-Minimum-Together-to-Deal-with-Minus | class Solution:
def maxProduct(self, nums: List[int]) -> int:
N = len(nums)
dpa = [0]*N
dpa[0] = nums[0]
dpb = [0]*N
dpb[0] = nums[0]
for i in range(1, N):
if nums[i] == 0:
dpa[i] = 0
dpb[i] = 0
else:
dpa[i] = max(dpb[i-1]*nums[i], dpa[i-1]*nums[i], nums[i])
dpb[i] = min(dpb[i-1]*nums[i], dpa[i-1]*nums[i], nums[i])
return max(dpa) | maximum-product-subarray | Dynamic Programming: Record Maximum and Minimum Together to Deal with Minus | hl2425 | 0 | 20 | maximum product subarray | 152 | 0.349 | Medium | 2,379 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1610126/python-3-oror-easy-soln-oror-clean-oror-beginner-oror-95.47-faster | class Solution:
def maxProduct(self, nums: List[int]) -> int:
res=max(nums)
cmin,cmax=1,1 #current min and max
for n in nums:
temp=cmax*n
cmax=max(n* cmax,n*cmin,n)
cmin=min(temp,n*cmin,n)
res=max(cmax,cmin,res)
return res | maximum-product-subarray | python 3 || easy soln || clean || beginner || 95.47% faster | minato_namikaze | 0 | 115 | maximum product subarray | 152 | 0.349 | Medium | 2,380 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1610119/Easy-multiply-and-remix-o(n)-solution | class Solution:
def maxProduct(self, nums):
_max = nums[0]
_min = nums[0]
result = nums[0]
for num in nums[1:]:
_max *= num
_min *= num
_max, _min = max(_max, _min, num), min(_max, _min, num)
result = max(result, _max)
return result | maximum-product-subarray | Easy multiply and remix o(n) solution | tamat | 0 | 38 | maximum product subarray | 152 | 0.349 | Medium | 2,381 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1467191/Python-simple-O(n)-time-O(1)-space-solution | class Solution:
def maxProduct(self, nums: List[int]) -> int:
localmax = nums[0]
globalmax = nums[0]
localmin = nums[0]
for i in range(1, len(nums)):
a = max(localmax*nums[i], nums[i], localmin*nums[i])
b = min(localmin*nums[i], nums[i], localmax*nums[i])
localmax = a
localmin = b
globalmax = max(globalmax, a, b)
return globalmax | maximum-product-subarray | Python simple O(n) time, O(1) space solution | byuns9334 | 0 | 259 | maximum product subarray | 152 | 0.349 | Medium | 2,382 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1427382/Extension-of-Kadane's-Algorithm | class Solution:
def maxProduct(self, nums: List[int]) -> int:
max_local = min_local = result = nums[0]
for i in range(1,len(nums)):
tmp = max_local
max_local = max(nums[i]*tmp,nums[i]*min_local,nums[i])
min_local = min(nums[i]*tmp,nums[i]*min_local,nums[i])
result = max(result,max_local)
return result | maximum-product-subarray | Extension of Kadane's Algorithm | manojkumarmanusai | 0 | 167 | maximum product subarray | 152 | 0.349 | Medium | 2,383 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1362212/GolangPython3-Clean-solution-O(n)-time-O(1)-space | class Solution:
def maxProduct(self, nums: List[int]) -> int:
_min = _max = res = nums[0]
for i in range(1, len(nums)):
if nums[i] < 0:
_min, _max = _max, _min
_min = min(nums[i], _min * nums[i])
_max = max(nums[i], _max * nums[i])
res = max(res, _max)
return res | maximum-product-subarray | [Golang/Python3] Clean solution - O(n) time, O(1) space | maosipov11 | 0 | 135 | maximum product subarray | 152 | 0.349 | Medium | 2,384 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1333785/Python-O(N)-Time-O(1)-Space-beats-90 | class Solution:
def maxProduct(self, nums: List[int]) -> int:
res = max(nums[0], nums[-1])
summ = nums[0] if nums[0] != 0 else 1
for pos in range(1, len(nums)):
if nums[pos] == 0:
summ = 1
res = max(res, 0)
else:
summ *= nums[pos]
res = max(summ, res)
summ = nums[-1] if nums[-1] != 0 else 1
for pos in range(len(nums)-2, -1, -1):
if nums[pos] == 0:
summ = 1
res = max(res, 0)
else:
summ *= nums[pos]
res = max(summ, res)
return res | maximum-product-subarray | Python O(N) Time O(1) Space beats 90% | IKM98 | 0 | 232 | maximum product subarray | 152 | 0.349 | Medium | 2,385 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1295716/My-Python-code-that-uses-the-same-idea-as-Solution-2-but-is-more-natural.-Beat-95.03 | class Solution:
def maxProduct(self, nums: List[int]) -> int:
maxprod = maxcurr = maxneg = 0
if nums[0] > 0:
maxprod = maxcurr = nums[0]
else:
maxprod = maxneg = nums[0]
for n in nums[1:]:
if n == 0:
maxcurr = maxneg = 0
elif n > 0:
maxcurr = maxcurr * n if maxcurr > 0 else n
maxneg = maxneg * n if maxneg < 0 else n
else:
temp = maxcurr
maxcurr = maxneg * n if maxneg < 0 else 0
maxneg = temp * n if temp > 0 else n
maxprod = max(maxprod, maxcurr)
return maxprod | maximum-product-subarray | My Python code that uses the same idea as Solution 2 but is more natural. Beat 95.03% | wanghua_wharton | 0 | 180 | maximum product subarray | 152 | 0.349 | Medium | 2,386 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1240396/Python3-simple-solution-beats-90-users | class Solution:
def maxProduct(self, nums: List[int]) -> int:
res = _max = _min = nums[0]
for i in range(1,len(nums)):
_max, _min = max(_max*nums[i], _min*nums[i], nums[i]), min(_max*nums[i], _min*nums[i], nums[i])
res = max(res, _max)
return res | maximum-product-subarray | Python3 simple solution beats 90% users | EklavyaJoshi | 0 | 75 | maximum product subarray | 152 | 0.349 | Medium | 2,387 |
https://leetcode.com/problems/maximum-product-subarray/discuss/1091114/My-solution-using-accumulate | class Solution:
def maxProduct(self, nums: List[int]) -> int:
f = lambda x, y: y if x == 0 else x * y
return max(max(accumulate(nums, f)), max(accumulate(nums[::-1], f))) | maximum-product-subarray | My solution using accumulate | dmb225 | 0 | 31 | maximum product subarray | 152 | 0.349 | Medium | 2,388 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2211586/Python3-simple-naive-solution-with-binary-search | class Solution:
def findMin(self, nums: List[int]) -> int:
start = 0
end = len(nums) - 1
if(nums[start] <= nums[end]):
return nums[0]
while start <= end:
mid = (start + end) // 2
if(nums[mid] > nums[mid+1]):
return nums[mid+1]
if(nums[mid-1] > nums[mid]):
return nums[mid]
if(nums[mid] > nums[0]):
start = mid + 1
else:
end = mid - 1
return nums[start] | find-minimum-in-rotated-sorted-array | 📌 Python3 simple naive solution with binary search | Dark_wolf_jss | 6 | 105 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,389 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2779546/Intuitive-Binary-Search-in-Python | class Solution:
def findMin(self, nums: List[int]) -> int:
hi, lo = len(nums) - 1, 0
while hi - 1 > lo:
mid = (hi + lo)//2
if nums[lo] > nums[mid]:
hi = mid
else: # drop must be to the left
lo = mid
if nums[hi] > nums[lo]:
return nums[0]
return nums[hi] | find-minimum-in-rotated-sorted-array | Intuitive Binary Search in Python | Abhi5415 | 3 | 205 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,390 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2564351/Python3-or-Intuitive-or-Optimal-or-Neat | class Solution:
def findMin(self, nums: List[int]) -> int:
l, r = 0, len(nums)-1
while l < r:
m = (l+r)//2
if nums[l] < nums[r]:
return nums[l]
else:
if l+1 == r:
return nums[r]
elif nums[l] < nums[m] and nums[m] > nums[r]:
l = m+1
else:
r = m
return nums[l] | find-minimum-in-rotated-sorted-array | Python3 | Intuitive | Optimal | Neat | aashi111989 | 2 | 144 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,391 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2022377/Python-Two-Solutionsor-Binary-Search-or-One-Liner | class Solution:
def findMin(self, nums: List[int]) -> int:
res = nums[0]
l, r = 0, len(nums) - 1
while l <= r:
if nums[l] < nums[r]:
res = min(res, nums[l])
break
m = (l + r) // 2
res = min(res, nums[m])
if nums[m] >= nums[l]:
l = m + 1
else:
r = m - 1
return res | find-minimum-in-rotated-sorted-array | Python Two Solutions| Binary Search | One-Liner | shikha_pandey | 2 | 162 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,392 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2625846/Best-and-fast-solution-in-PYTHON | class Solution:
def findMin(self, num):
first, last = 0, len(num) - 1
while first < last:
midpoint = (first + last) // 2
if num[midpoint] > num[last]:
first = midpoint + 1
else:
last = midpoint
return num[first]
``` | find-minimum-in-rotated-sorted-array | Best and fast solution in PYTHON | Ankitjoshi222 | 1 | 149 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,393 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2147271/2-methods-or-Python-3-or-Easy-solution-with-explanation | class Solution:
def findMin(self, nums: List[int]) -> int:
return min(nums) | find-minimum-in-rotated-sorted-array | 2 methods | Python 3 | Easy solution with explanation | yashkumarjha | 1 | 66 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,394 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2147271/2-methods-or-Python-3-or-Easy-solution-with-explanation | class Solution:
def findMin(self, nums: List[int]) -> int:
# Go in loop from index 1 till end.
for i in range(1,len(nums)):
# Checking if nums[i] is less than the first element of the list.
if(nums[0]>nums[i]):
# If yes then return that element.
return nums[i]
# Otherwise if all the loop ends and condition doesn't matches then return the 0th index element.
return nums[0] | find-minimum-in-rotated-sorted-array | 2 methods | Python 3 | Easy solution with explanation | yashkumarjha | 1 | 66 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,395 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/1991222/Basic-Binary-Search-Python-Solution-greater-90 | class Solution(object):
def findMin(self, nums):
l = 0
r = len(nums)-1
#special case --> array is not rotated
if(nums[0]<=nums[len(nums)-1]):
return nums[0]
while(l<=r):
mid = (l+r)//2
if(nums[mid]<nums[mid-1]):
return nums[mid]
elif(nums[mid]<nums[0]):
r = mid-1
else:
l = mid+1 | find-minimum-in-rotated-sorted-array | Basic Binary Search Python Solution > 90% | felixplease | 1 | 56 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,396 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/1890202/python-3-oror-binary-search | class Solution:
def findMin(self, nums: List[int]) -> int:
n = len(nums)
if n == 1:
return nums[0]
left, right = 0, n - 1
while True:
mid = (left + right) // 2
if ((mid != n - 1 and nums[mid-1] > nums[mid] < nums[mid+1]) or
(mid == n - 1 and nums[mid-1] > nums[mid] < nums[0])):
return nums[mid]
elif nums[mid] < nums[right]:
right = mid - 1
else:
left = mid + 1 | find-minimum-in-rotated-sorted-array | python 3 || binary search | dereky4 | 1 | 111 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,397 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/1660793/Python-binary-search | class Solution:
def findMin(self, nums: List[int]) -> int:
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] >= nums[0]:
l = mid + 1
else:
r = mid - 1
return nums[l] if l < len(nums) else nums[0] | find-minimum-in-rotated-sorted-array | Python, binary search | blue_sky5 | 1 | 48 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,398 |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/1540292/Very-easy-and-efficient-solution | class Solution:
def findMin(self, nums: List[int]) -> int:
#If the array is sorted, there is no rotation
rotate = 1
for i in range (len(nums)-1):
#Checking whether full array is sorted or not
if nums[i] < nums [i+1]:
continue
# When the array is not sorted, it will return the first small element
elif nums[i] > nums [i+1] :
out = nums[i+1]
rotate = 2
break
#if the array is sorted, first element will be the smallest element
if rotate == 1:
return nums[0]
else:
return out | find-minimum-in-rotated-sorted-array | Very easy and efficient solution | stormbreaker_x | 1 | 52 | find minimum in rotated sorted array | 153 | 0.485 | Medium | 2,399 |
Subsets and Splits