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/maximum-average-pass-ratio/discuss/1108316/Python3-greedy-(priority-queue)
class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: pq = [(p/t - (p+1)/(t+1), p, t) for p, t in classes] # max-heap heapify(pq) for _ in range(extraStudents): _, p, t = heappop(pq) heappush(pq, ((p+1)/(t+1) - (p+2)/(t+2), p+1, t+1)) return sum(p/t for _, p, t in pq)/len(pq)
maximum-average-pass-ratio
[Python3] greedy (priority queue)
ye15
1
90
maximum average pass ratio
1,792
0.521
Medium
25,700
https://leetcode.com/problems/maximum-average-pass-ratio/discuss/1108272/Python3-Priority-Queue-solution-with-thought-process
class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: pq = [] for i, stat in enumerate(classes): score = (stat[1]-stat[0])/(stat[1]*(stat[1]+1)) heapq.heappush(pq, (-score, i)) while extraStudents: _, idx = heapq.heappop(pq) classes[idx][0] += 1 classes[idx][1] += 1 newScore = (classes[idx][1]-classes[idx][0])/(classes[idx][1]*(classes[idx][1]+1)) heapq.heappush(pq, (-newScore, idx)) extraStudents -= 1 return sum(stat[0]/stat[1] for stat in classes)/len(classes)
maximum-average-pass-ratio
[Python3] Priority Queue solution with thought process
hwsbjts
1
85
maximum average pass ratio
1,792
0.521
Medium
25,701
https://leetcode.com/problems/maximum-average-pass-ratio/discuss/2779723/python-max-heap
class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: max_heap = [] for student, total in classes: heappush(max_heap, (student / total - (student + 1) / (total + 1), student, total)) for i in range(extraStudents): r, s, t = heappop(max_heap) heappush(max_heap, ((s + 1) / (t + 1) - (s + 2) / (t + 2), s + 1, t + 1)) return sum(i[1] / i[2] for i in max_heap) / len(max_heap)
maximum-average-pass-ratio
python max heap
JasonDecode
0
1
maximum average pass ratio
1,792
0.521
Medium
25,702
https://leetcode.com/problems/maximum-average-pass-ratio/discuss/1788093/Python-or-Priority-Queue
class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: pq=[] for pss,tot in classes: newratio=(pss+1)/(tot+1) currratio=pss/tot pq.append((-(newratio-currratio),pss,tot)) heapq.heapify(pq) ans=0 while extraStudents>0: _,pss,tot=heapq.heappop(pq) pss+=1 tot+=1 extraStudents-=1 currratio=pss/tot newratio=(pss+1)/(tot+1) heapq.heappush(pq,(-(newratio-currratio),pss,tot)) for _,p,q in pq: ans+=p/q return ans/len(pq)
maximum-average-pass-ratio
Python | Priority Queue
heckt27
0
79
maximum average pass ratio
1,792
0.521
Medium
25,703
https://leetcode.com/problems/maximum-average-pass-ratio/discuss/1342450/Heap-for-ratio-change-98-speed
class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: heap_classes = [] for p, t in classes: heappush(heap_classes, (-((p + 1) / (t + 1) - p / t), p, t)) for _ in range(extraStudents): diff, p, t = heappop(heap_classes) p += 1 t += 1 heappush(heap_classes, (-((p + 1) / (t + 1) - p / t), p, t)) return sum(p / t for d, p, t in heap_classes) / len(classes)
maximum-average-pass-ratio
Heap for ratio change, 98% speed
EvgenySH
0
196
maximum average pass ratio
1,792
0.521
Medium
25,704
https://leetcode.com/problems/maximum-score-of-a-good-subarray/discuss/1108326/Python3-greedy-(2-pointer)
class Solution: def maximumScore(self, nums: List[int], k: int) -> int: ans = mn = nums[k] lo = hi = k while 0 <= lo-1 or hi+1 < len(nums): if lo == 0 or hi+1 < len(nums) and nums[lo-1] < nums[hi+1]: hi += 1 mn = min(mn, nums[hi]) else: lo -= 1 mn = min(mn, nums[lo]) ans = max(ans, mn * (hi-lo+1)) return ans
maximum-score-of-a-good-subarray
[Python3 ] greedy (2-pointer)
ye15
9
300
maximum score of a good subarray
1,793
0.535
Hard
25,705
https://leetcode.com/problems/maximum-score-of-a-good-subarray/discuss/1110862/Easy-stack-solution
class Solution: def maximumScore(self, nums: List[int], k: int) -> int: N = len(nums) def next_small_left(): i = 0 left=[-1]*N stack=[] for i in range(N): while stack and nums[stack[-1]] >= nums[i]: stack.pop() if stack: left[i] = stack[-1] stack.append(i) return left def next_small_right(): right=[N]*N stack=[] for i in range(N-1,-1,-1): while stack and nums[stack[-1]] >= nums[i]: stack.pop() if stack: right[i] = stack[-1] stack.append(i) return right left = next_small_left() right = next_small_right() # print(left,right) N = len(left) ans=-1 for i in range(N): if left[i]+1 <= k <= right[i]-1: ans = max(ans,(right[i]-left[i]-1)*nums[i]) # print(i,ans) return ans
maximum-score-of-a-good-subarray
Easy stack solution
bismeet
2
122
maximum score of a good subarray
1,793
0.535
Hard
25,706
https://leetcode.com/problems/maximum-score-of-a-good-subarray/discuss/2660450/Stack-Solution-Largest-Rectangle-in-Histogram-Python
class Solution: def maximumScore(self, nums: List[int], k: int) -> int: def nsr(arr): ans=[] stack=[] for i in range(len(arr)-1,-1,-1): while stack and arr[stack[-1]]>=arr[i]: stack.pop() if not stack: ans.append(len(arr)) else: ans.append(stack[-1]) stack.append(i) return ans[::-1] def nsl(arr): ans=[] stack=[] for i in range(len(arr)): while stack and arr[stack[-1]]>=arr[i]: stack.pop() if not stack: ans.append(-1) else: ans.append(stack[-1]) stack.append(i) return ans nslArr= nsl(nums) nsrArr= nsr(nums) score =0 #here we are finding the nearest smaller to the left and to the right #because we want to maximize and for a number we find its minimum from both side and take +1 index from left and -1 index from the right #and for the range r-l-1 - #for the length it is r-l+1 but we are removing the l and r because these are the minimum so r-l+1-2 -> r-l-1 for i in range(len(nums)): l = nslArr[i] r = nsrArr[i] if l+1<=k and r-1>=k: score=max(score,nums[i]*(r-l-1)) return score
maximum-score-of-a-good-subarray
Stack Solution, Largest Rectangle in Histogram - Python
prateekgoel7248
1
30
maximum score of a good subarray
1,793
0.535
Hard
25,707
https://leetcode.com/problems/maximum-score-of-a-good-subarray/discuss/2159323/Two-Pointer-oror-Greedy-oror-Linear-Time
class Solution: def maximumScore(self, nums: List[int], k: int) -> int: length = len(nums) maximumPossibleScore = nums[k] minimum = nums[k] left = k right = k while left > 0 or right < length - 1: if left > 0 and right < length - 1: if nums[left - 1] > nums[right + 1]: left -= 1 minimum = min(minimum, nums[left]) else: right += 1 minimum = min(minimum, nums[right]) elif left > 0: left -= 1 minimum = min(minimum, nums[left]) else: right += 1 minimum = min(minimum, nums[right]) score = minimum*(right-left+1) maximumPossibleScore = max(maximumPossibleScore, score) return maximumPossibleScore
maximum-score-of-a-good-subarray
Two Pointer || Greedy || Linear Time
Vaibhav7860
1
94
maximum score of a good subarray
1,793
0.535
Hard
25,708
https://leetcode.com/problems/maximum-score-of-a-good-subarray/discuss/2831301/python-the-same-solution-but-less-if-else
class Solution: def maximumScore(self, nums: List[int], k: int) -> int: nums = [0] + nums + [0] i = j = k+1 res, n = 0, nums[i] while n: while n <= nums[i]: i -= 1 while n <= nums[j]: j += 1 res = max(res, n * (j-i-1)) n = max(nums[i], nums[j]) return res
maximum-score-of-a-good-subarray
[python] the same solution but less if-else
pukras
0
2
maximum score of a good subarray
1,793
0.535
Hard
25,709
https://leetcode.com/problems/maximum-score-of-a-good-subarray/discuss/1595670/Python%3A-T%3A-O(n)-and-S%3A-O(1)-with-88.89-and-99.59.
class Solution: def maximumScore(self, n: List[int], kk: int) -> int: vmin = n[kk] for i in range(kk,-1,-1): if n[i]<vmin: vmin = n[i] else: n[i] = vmin vmin = n[kk] for i in range(kk,len(n)): if n[i]<vmin: vmin = n[i] else: n[i] = vmin good = 0 li = 0 ri = len(n)-1 while li<=kk and ri>= kk: vmin = min(n[li],n[ri]) if vmin*(ri-li+1)>good: good = min(n[li],n[ri])*(ri-li+1) if li == ri: break while li<kk and n[li]==vmin: li += 1 while ri>kk and n[ri]==vmin: ri -= 1 return good
maximum-score-of-a-good-subarray
Python: T: O(n) and S: O(1) with 88.89% and 99.59%.
jijnasu
0
101
maximum score of a good subarray
1,793
0.535
Hard
25,710
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1739076/Python3-or-Faster-Solution-or-Easiest-or-brute-force
class Solution: def secondHighest(self, s: str) -> int: s=set(s) a=[] for i in s: if i.isnumeric() : a.append(int(i)) a.sort() if len(a)<2: return -1 return a[len(a)-2]
second-largest-digit-in-a-string
✔ Python3 | Faster Solution | Easiest | brute force
Anilchouhan181
5
184
second largest digit in a string
1,796
0.491
Easy
25,711
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1230218/Python3-simple-solution-using-list
class Solution: def secondHighest(self, s: str) -> int: l = [] for i in s: if i.isdigit() and i not in l: l.append(i) if len(l) >= 2: return int(sorted(l)[-2]) else: return -1
second-largest-digit-in-a-string
Python3 simple solution using list
EklavyaJoshi
4
138
second largest digit in a string
1,796
0.491
Easy
25,712
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1731838/Python-3-(30ms)-or-Fastest-Set-Solution-or-Easy-to-Understand
class Solution: def secondHighest(self, s: str) -> int: st = (set(s)) f1,s2=-1,-1 for i in st: if i.isnumeric(): i=int(i) if i>f1: s2=f1 f1=i elif i>s2 and i!=f1: s2=i return s2
second-largest-digit-in-a-string
Python 3 (30ms) | Fastest Set Solution | Easy to Understand
MrShobhit
3
82
second largest digit in a string
1,796
0.491
Easy
25,713
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1739099/Python3-or-Without-array-or-sorting-or-Faster-Solution-or-Easiest
class Solution: def secondHighest(self, s: str) -> int: st = (set(s)) f1,s2=-1,-1 for i in st: if i.isnumeric(): i=int(i) if i>f1: s2=f1 f1=i elif i>s2 and i!=f1: s2=i return s2
second-largest-digit-in-a-string
✔ Python3 | Without array or sorting | Faster Solution | Easiest
Anilchouhan181
2
58
second largest digit in a string
1,796
0.491
Easy
25,714
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1139817/python-one-liner
class Solution: def secondHighest(self, s: str) -> int: return ([-1, -1] + sorted(set(int(c) for c in s if c.isdigit())))[-2]
second-largest-digit-in-a-string
python one-liner
leetcoder289
2
178
second largest digit in a string
1,796
0.491
Easy
25,715
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2794291/PYTHON-oror-EASY-TO-UNDERSTAND
class Solution: def secondHighest(self, s: str) -> int: lst = [] for i in range(len(s)): if s[i].isdigit(): lst.append(s[i]) lst = list(set(lst)) if len(lst) <= 1: return -1 else: lst.sort() index = len(lst)-2 res = lst[index] return res
second-largest-digit-in-a-string
PYTHON || EASY TO UNDERSTAND
thesunnysinha
1
44
second largest digit in a string
1,796
0.491
Easy
25,716
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1989368/Python3-or-Simple-solution-with-explanation
class Solution: def secondHighest(self, s: str) -> int: b=[] # Creating a list of only numbers in the string for i in set(s): # Using set speeds up the loop by only taking unique characters if i.isnumeric(): # Built in function to check if an element is a number b.append(i) # Sorting the list in descending order b.sort(reverse=True) # Checking if the length of the list is greater than 2 if len(b)>=2: return b[1] # Return second largest else: return -1
second-largest-digit-in-a-string
Python3 | Simple solution with explanation
mopasha1
1
38
second largest digit in a string
1,796
0.491
Easy
25,717
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1902972/Clean-and-Easiest-Python-3-oror-Faster-Solution-oror-Combination-use-of-List-and-Set-oror-Straight-Forward
class Solution: def secondHighest(self, s: str) -> int: temp=[] res={} largest=0 sec_largest=0 for i in s: if i.isdigit(): c=int(i) temp.append(c) temp.sort() res=set(temp) temp=list(res) if len(temp)>1: for i in temp: if largest<i: sec_largest=largest largest=i elif i>=sec_largest: sec_largest=i return (sec_largest) else: return (-1)
second-largest-digit-in-a-string
Clean & Easiest Python 3 || Faster Solution || Combination use of List and Set || Straight Forward
RatnaPriya
1
36
second largest digit in a string
1,796
0.491
Easy
25,718
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2814923/Optimal-and-Clean-with-explanation-2-ways%3A-O(n)-time-and-O(1)-space
class Solution: # Optimal: O(n) time and O(1) space: # 2 cases: # 1. digit d > max : max = d, second_max = max # 2. d != max and d > second_max : second_max = d # O(n) time : O(n) space def secondHighest(self, s: str) -> int: digits = [int(d) for d in s if d.isdigit()] max_ = max(digits, default = -1) return max([d for d in digits if d != max_], default = -1) # O(n) time : O(1) space def secondHighest(self, s: str) -> int: max_, second_max = -1, -1 for d in s: if d.isdigit(): if int(d) > max_: max_, second_max = int(d), max_ elif int(d) != max_ and int(d) > second_max: #int(d) != max_ is needed for 'second DISTINCT max' second_max = int(d) return second_max
second-largest-digit-in-a-string
Optimal and Clean with explanation - 2 ways: O(n) time and O(1) space
topswe
0
2
second largest digit in a string
1,796
0.491
Easy
25,719
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2808418/2-ways%3A-OptimalClean-O(n)-time-%3A-O(1)-space-solution-Python
class Solution: # O(n) time : O(n) space def secondHighest(self, s: str) -> int: digits = [int(d) for d in s if d.isdigit()] max_ = max(digits, default = -1) return max([d for d in digits if d != max_], default = -1) # O(n) time : O(1) space def secondHighest(self, s: str) -> int: max_, second_max = -1, -1 for d in s: if d.isdigit(): if int(d) > max_: max_, second_max = int(d), max_ elif int(d) != max_ and int(d) > second_max: #int(d) != max_ is needed for 'second DISTINCT max' second_max = int(d) return second_max
second-largest-digit-in-a-string
2 ways: Optimal/Clean O(n) time : O(1) space solution Python
topswe
0
2
second largest digit in a string
1,796
0.491
Easy
25,720
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2784072/Python-Set()-Solution
class Solution: def secondHighest(self, s: str) -> int: result = set() for char in s: if char.isdigit(): result.add(int(char)) if len(result) <= 1: return -1 max_digit = max(result) result.remove(max_digit) second_max_digit = max(result) return second_max_digit
second-largest-digit-in-a-string
Python Set() Solution
namashin
0
2
second largest digit in a string
1,796
0.491
Easy
25,721
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2747611/Python-Clean-2-Liner
class Solution: def secondHighest(self, s: str) -> int: temp = set([i for i in s if i.isalpha()==False]) return sorted(temp)[-2] if len(temp)>1 else -1
second-largest-digit-in-a-string
Python Clean 2 Liner
izh_17
0
5
second largest digit in a string
1,796
0.491
Easy
25,722
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2709982/Python-solution-clean-code-with-full-comments.-96.81-space.
class Solution: def secondHighest(self, s: str) -> int: return find_second_max(list(set(filter_integers(s)))) # Send the list containing the integers to this function that will return the second max value. def find_second_max(x): max_1 = -1 max_2 = -1 for i in range(len(x)): if max_1 <= x[i]: max_2 = max_1 max_1 = x[i] elif (max_2 <= x[i]) and (x[i] <= max_1): max_2 = x[i] return max_2 # Iterate the given alphanumeric string and search for integers in string format. def filter_integers(s: str): result = [] for i in s: # Check if the current char is a digit. if i.isdigit(): # If so, then append the digit into the list, but as an integers value. result.append(int(i)) return result # Runtime: 73 ms, faster than 44.20% of Python3 online submissions for Second Largest Digit in a String. # Memory Usage: 13.8 MB, less than 96.81% of Python3 online submissions for Second Largest Digit in a String. # If you like my work and found it helpful, then I'll appreciate a like. Thanks!
second-largest-digit-in-a-string
Python solution, clean code with full comments. 96.81% space.
375d
0
16
second largest digit in a string
1,796
0.491
Easy
25,723
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2677011/Python3-Solution-oror-O(N)-Time-and-O(1)-Space-Complexity
class Solution: def secondHighest(self, s: str) -> int: lar1=-1 lar2=-1 for i in s: if i.isdigit(): if lar1<int(i): if lar1!=-1: lar2=lar1 lar1=int(i) elif lar2<int(i)<lar1: lar2=int(i) return lar2
second-largest-digit-in-a-string
Python3 Solution || O(N) Time & O(1) Space Complexity
akshatkhanna37
0
2
second largest digit in a string
1,796
0.491
Easy
25,724
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2544493/Python-3-Short-Straightforward-%2B-Comments
class Solution: def secondHighest(self, s: str) -> int: digits=list(set([int(x) for x in s if x.isdigit()])) # 1. create list of digits (used list comprehension, but truthfully it's just a snobby for loop) # 2. convert to set() so only unique values remain # 3. convert back to list digits.sort() # sort the list so values are increasing if len(digits)<=1: return -1 # this would occur if a single unique or no digits were in the string # ex1: "a1b1c1d1" # ex2: "abcd" else: return digits[-2] # an index of [-1] returns the last of a list, [-2] second to last, so on and so forth
second-largest-digit-in-a-string
[Python 3] Short, Straightforward + Comments
pvco
0
7
second largest digit in a string
1,796
0.491
Easy
25,725
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2478620/Python3-No-hash-table-approach-with-comments
class Solution: def secondHighest(self, s: str) -> int: first = second = -1 # Loop through each item in the string. Use .find() to determine if it is a number for item in s: if "1234567890".find(item) != -1: # If the number is greater than our highest so far, set first to it, and second to what first used to be if int(item) > first: first, second = int(item), first # If the number is greater than the second highest (but not the first), change second to this number elif int(item) > second and int(item) != first: second = int(item) # Return our second highest number return second
second-largest-digit-in-a-string
[Python3] No hash table approach with comments
connorthecrowe
0
23
second largest digit in a string
1,796
0.491
Easy
25,726
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2424226/Python-Easy-Solution
class Solution: def secondHighest(self, s: str) -> int: l=[] for i in s: if i.isdigit(): l.append(int(i)) k=sorted(list(set(l))) if len(k)<=1: return -1 else: return k[-2]
second-largest-digit-in-a-string
Python Easy Solution
abhint1
0
17
second largest digit in a string
1,796
0.491
Easy
25,727
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2420402/Python-Simple-Solution-(-95-Fast-)
class Solution: def secondHighest(self, s: str) -> int: l = [] for i in s: if i.isdigit(): l.append(i) x = sorted(list(set(l))) if (len(x) == 1 ) or (l == []): return -1 return x[-2]
second-largest-digit-in-a-string
Python Simple Solution ( 95% Fast )
SouravSingh49
0
11
second largest digit in a string
1,796
0.491
Easy
25,728
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2237397/Beginner-Friendly-Solution-oror-33ms-Faster-Than-98-oror-Python
class Solution: def secondHighest(self, s: str) -> int: # Initialize a list to collect the unique digits in. lst = [] # Check each character of s. Only collect digits that are not already in lst. for i in s: if i.isdigit() and i not in lst: lst.append(i) # EDGE_CASE -- lst doesn't contain any digits, or only contains one digit. if 0 <= len(lst) <=1: return -1 # Remove the largest digit in lst. lst.remove(max(lst)) # Now, the second largest digit is the largest in lst. Return that digit. return max(lst)
second-largest-digit-in-a-string
Beginner Friendly Solution || 33ms, Faster Than 98% || Python
cool-huip
0
38
second largest digit in a string
1,796
0.491
Easy
25,729
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2188953/Faster-than-99-python-solution-for-beginners
class Solution: def secondHighest(self, s: str) -> int: output = [] for l in s: if l.isdigit(): output.append(int(l)) output = sorted(list(set(output))) if len(output) < 2: return -1 return output[-2]
second-largest-digit-in-a-string
Faster than 99% python solution for beginners
pro6igy
0
39
second largest digit in a string
1,796
0.491
Easy
25,730
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/2104006/Python-oneliner
class Solution: def secondHighest(self, s: str) -> int: import re return sorted(list({int(x) for x in re.split(r'[^0-9]*',s) if x}))[-2] if len({int(x) for x in re.split(r'[^0-9]*',s) if x}) > 1 else -1
second-largest-digit-in-a-string
Python oneliner
StikS32
0
37
second largest digit in a string
1,796
0.491
Easy
25,731
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1922152/Python-easy-solution-for-beginners
class Solution: def secondHighest(self, s: str) -> int: dig = [] for i in s: if i.isnumeric() and int(i) not in dig: dig.append(int(i)) if len(dig) < 2: return -1 dig.sort(reverse=True) return dig[1]
second-largest-digit-in-a-string
Python easy solution for beginners
alishak1999
0
49
second largest digit in a string
1,796
0.491
Easy
25,732
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1919756/Python3-or-faster-than-99
class Solution: def secondHighest(self, s: str) -> int: digits=sorted(set([int(c) for c in s if c.isdigit()]),reverse=True) return digits[1] if len(digits)>=2 else -1
second-largest-digit-in-a-string
Python3 | faster than 99%
ginaaunchat
0
28
second largest digit in a string
1,796
0.491
Easy
25,733
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1910558/Python-Solution
class Solution: def secondHighest(self, s: str) -> int: result = sorted(set(''.join(filter(lambda x: x.isdigit(), s)))) return result[-2] if len(result) > 1 else -1
second-largest-digit-in-a-string
Python Solution
hgalytoby
0
25
second largest digit in a string
1,796
0.491
Easy
25,734
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1859121/Python-dollarolution-(93-Faster-and-96-Mem-use)
class Solution: def secondHighest(self, s: str) -> int: v = [] for i in s: if i.isnumeric(): v.append(i) try: return sorted(set(v),reverse = True)[1] except: return -1
second-largest-digit-in-a-string
Python $olution (93% Faster and 96% Mem use)
AakRay
0
38
second largest digit in a string
1,796
0.491
Easy
25,735
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1578300/Python3-Solution-faster-than-99.53
class Solution: def secondHighest(self, s: str) -> int: arr = list(set([c for c in s if c.isdigit()])) if len(arr) > 1: arr.remove(max(arr)) return max(arr) else: return -1
second-largest-digit-in-a-string
Python3 Solution faster than 99.53%
risabhmishra19
0
36
second largest digit in a string
1,796
0.491
Easy
25,736
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1488527/2-solutions-in-Python-using-O(n)-and-O(1)-space-respectively
class Solution: def secondHighest(self, s: str) -> int: digits = sorted(set(c for c in s if c.isdigit())) try: return int(digits[-2]) except IndexError: return -1
second-largest-digit-in-a-string
2 solutions in Python, using O(n) and O(1) space respectively
mousun224
0
63
second largest digit in a string
1,796
0.491
Easy
25,737
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1488527/2-solutions-in-Python-using-O(n)-and-O(1)-space-respectively
class Solution: def secondHighest(self, s: str) -> int: digits, msb_index = 0, -1 for c in s: if c.isdigit(): digits |= (1 << int(c)) for i, c in enumerate(f"{digits:b}", start=1): if c == "1": if msb_index != -1: return digits.bit_length() - i msb_index = i return -1
second-largest-digit-in-a-string
2 solutions in Python, using O(n) and O(1) space respectively
mousun224
0
63
second largest digit in a string
1,796
0.491
Easy
25,738
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1368178/Python3-solution
class Solution: def secondHighest(self, s: str) -> int: my_set = set() for i, element in enumerate(s): if s[i].isdigit() == True: my_set.add(s[i]) if len(my_set) <= 1: return -1 else: my_set.remove(max(my_set)) return max(my_set)
second-largest-digit-in-a-string
Python3 solution
FlorinnC1
0
42
second largest digit in a string
1,796
0.491
Easy
25,739
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1122796/Python-set-compehension
class Solution: def secondHighest(self, s: str) -> int: integers = sorted({int(char) for char in s if char.isdigit()}) if len(integers) > 1: return integers[-2] return -1
second-largest-digit-in-a-string
Python set compehension
alexanco
0
53
second largest digit in a string
1,796
0.491
Easy
25,740
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1119514/Intuitive-approach-by-collecting-character-as-numeric-and-sorting-them
class Solution: def secondHighest(self, s: str) -> int: digit_set = set() for c in s: if c.isnumeric(): digit_set.add(c) nums = sorted(list(map(lambda e: int(e), digit_set)), reverse=True) return nums[1] if len(nums) > 1 else -1
second-largest-digit-in-a-string
Intuitive approach by collecting character as numeric and sorting them
puremonkey2001
0
23
second largest digit in a string
1,796
0.491
Easy
25,741
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1119222/Python3-Solution
class Solution: def secondHighest(self, s: str) -> int: s = sorted(set([int(c) for c in s if c.isdigit()]), reverse=True) if s and len(s) >=2: return s[1] return -1
second-largest-digit-in-a-string
Python3 Solution
cppygod
0
66
second largest digit in a string
1,796
0.491
Easy
25,742
https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1118746/Python3-hash-set
class Solution: def secondHighest(self, s: str) -> int: seen = set() for c in s: if c.isdigit(): seen.add(int(c)) return -1 if len(seen) < 2 else sorted(seen)[-2]
second-largest-digit-in-a-string
[Python3] hash set
ye15
0
50
second largest digit in a string
1,796
0.491
Easy
25,743
https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/discuss/1153726/Python3-Simple-Solution
class Solution: def getMaximumConsecutive(self, coins: List[int]) -> int: coins.sort() res = 1 for coin in coins: if (res >= coin): res += coin return res
maximum-number-of-consecutive-values-you-can-make
Python3 Simple Solution
victor72
1
154
maximum number of consecutive values you can make
1,798
0.545
Medium
25,744
https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/discuss/1118844/python3-Sorting-O(nlogn)-solution
class Solution: def getMaximumConsecutive(self, coins: List[int]) -> int: coins.sort() ans = 0 for i in range(len(coins)): if coins[i]<=ans+1: ans += coins[i] else: break return ans+1
maximum-number-of-consecutive-values-you-can-make
python3 Sorting O(nlogn) solution
swap2001
1
138
maximum number of consecutive values you can make
1,798
0.545
Medium
25,745
https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/discuss/1118773/Python3-greedy
class Solution: def getMaximumConsecutive(self, coins: List[int]) -> int: ans = 1 for x in sorted(coins): if ans < x: break ans += x return ans
maximum-number-of-consecutive-values-you-can-make
[Python3] greedy
ye15
1
145
maximum number of consecutive values you can make
1,798
0.545
Medium
25,746
https://leetcode.com/problems/maximize-score-after-n-operations/discuss/1118782/Python3-dp
class Solution: def maxScore(self, nums: List[int]) -> int: @cache def fn(nums, k): """Return max score from nums at kth step.""" if not nums: return 0 # boundary condition ans = 0 for i in range(len(nums)): for j in range(i+1, len(nums)): rest = nums[:i] + nums[i+1:j] + nums[j+1:] ans = max(ans, k*gcd(nums[i], nums[j]) + fn(tuple(rest), k+1)) return ans return fn(tuple(nums), 1)
maximize-score-after-n-operations
[Python3] dp
ye15
17
1,500
maximize score after n operations
1,799
0.458
Hard
25,747
https://leetcode.com/problems/maximize-score-after-n-operations/discuss/1118782/Python3-dp
class Solution: def maxScore(self, nums: List[int]) -> int: n = len(nums) @cache def fn(mask, k): """Return maximum score at kth operation with available numbers by mask.""" if mask == 0: return 0 # no more numbers ans = 0 for i in range(n): if mask &amp; 1 << i: for j in range(i+1, n): if mask &amp; 1 << j: mask0 = mask &amp; ~(1<<i) &amp; ~(1<<j) # unset ith &amp; jth bit ans = max(ans, k*gcd(nums[i], nums[j]) + fn(mask0, k+1)) return ans return fn((1<<n) - 1, 1)
maximize-score-after-n-operations
[Python3] dp
ye15
17
1,500
maximize score after n operations
1,799
0.458
Hard
25,748
https://leetcode.com/problems/maximize-score-after-n-operations/discuss/2594805/Simple-DP-implementation-in-Python
class Solution: @cache def gcd(self, a, b): return self.gcd(b, a) if b else a @cache def dfs(self, t, used): score = 0 for i in range(len(self.nums)-1): if (1 << i) &amp; used: continue for j in range(i+1, len(self.nums)): if (1 << j) &amp; used: continue score = max(score, t * gcd(self.nums[i], self.nums[j]) + self.dfs(t+1, used | (1 << i) | (1 << j))) return score def maxScore(self, nums: List[int]) -> int: self.nums = nums return self.dfs(1, 0)
maximize-score-after-n-operations
Simple DP implementation in Python
metaphysicalist
0
22
maximize score after n operations
1,799
0.458
Hard
25,749
https://leetcode.com/problems/maximize-score-after-n-operations/discuss/1307228/Python-Bitmask-DP
class Solution: def maxScore(self, nums: List[int]) -> int: def combination(count=1, bitmask=0): if count==size//2+1: return 0 max_ = 0 for i in range(size): if bitmask>>i&amp;1: continue newBitmask = bitmask|1<<i for j in range(size): if newBitmask>>j&amp;1: continue newBitmask = bitmask|1<<i|1<<j if dp[newBitmask]: max_ = max(max_, table[i][j]*count+dp[newBitmask]) else: max_ = max(max_, table[i][j]*count+combination(count+1, newBitmask)) dp[bitmask] = max_ return max_ size = len(nums) dp = [0]*(2**size) table = [[0]*size for i in range(size)] for i in range(size): for j in range(i+1, size): table[i][j] = table[j][i] = math.gcd(nums[i], nums[j]) return combination()
maximize-score-after-n-operations
Python Bitmask DP
johnnylu305
0
433
maximize score after n operations
1,799
0.458
Hard
25,750
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1119686/Python3-line-sweep
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: ans = 0 for i, x in enumerate(nums): if not i or nums[i-1] >= nums[i]: val = 0 # reset val val += nums[i] ans = max(ans, val) return ans
maximum-ascending-subarray-sum
[Python3] line sweep
ye15
6
617
maximum ascending subarray sum
1,800
0.637
Easy
25,751
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1204617/Python3-simple-solution-beats-90-users
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: sum = nums[0] x = nums[0] i = 1 while i < len(nums): if nums[i] > nums[i-1]: x += nums[i] else: x = nums[i] sum = max(x,sum) i += 1 return sum
maximum-ascending-subarray-sum
Python3 simple solution beats 90% users
EklavyaJoshi
3
128
maximum ascending subarray sum
1,800
0.637
Easy
25,752
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1283162/Python3-O(n)-one-loop
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: result = 0 count = 0 for i in range(len(nums) + 1): if i != 0: if result < count: result = count if i != len(nums): if nums[i - 1] >= nums[i]: count = 0 if i != len(nums): count += nums[i] return result
maximum-ascending-subarray-sum
Python3 - O(n), one loop
CC_CheeseCake
2
165
maximum ascending subarray sum
1,800
0.637
Easy
25,753
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1126385/Python-3-Simple-Solution-Faster-than-96.22
class Solution: def maxAscendingSum(self, l: List[int]) -> int: ms=l[0] cs=l[0] for i in range(1,len(l)): if l[i]<=l[i-1]: cs=l[i] else: cs+=l[i] ms=max(cs,ms) # print(ms,i) return ms
maximum-ascending-subarray-sum
Python 3 Simple Solution Faster than 96.22%
Anurag_Tiwari
2
258
maximum ascending subarray sum
1,800
0.637
Easy
25,754
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/2102983/PYTHON-or-Simple-python-solution
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: maxSum = 0 subSum = 0 for i in range(len(nums)): if i == 0 or nums[i-1] < nums[i]: subSum += nums[i] maxSum = max(maxSum, subSum) else: subSum = nums[i] return maxSum
maximum-ascending-subarray-sum
PYTHON | Simple python solution
shreeruparel
1
95
maximum ascending subarray sum
1,800
0.637
Easy
25,755
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1272947/Clear-python3-sliding-window-max-subarray-code-easy-to-understand-beats-94
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: total = maxSoFar = 0 last = nums[0] - 1 for x in nums: if x > last: total += x else: maxSoFar = max(maxSoFar, total) total = x last = x maxSoFar = max(maxSoFar, total) return maxSoFar
maximum-ascending-subarray-sum
Clear python3 sliding window max subarray code, easy to understand, beats 94%
rsha256
1
42
maximum ascending subarray sum
1,800
0.637
Easy
25,756
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1189362/Python3-simple-solution
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: maxSum = nums[0] localSum = nums[0] for i in range(1,len(nums)): if nums[i] > nums[i-1]: localSum += nums[i] else: localSum = nums[i] if localSum > maxSum: maxSum = localSum return maxSum
maximum-ascending-subarray-sum
Python3 simple solution
sunnysharma03
1
65
maximum ascending subarray sum
1,800
0.637
Easy
25,757
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/2690437/Easy-and-Optimal-Faster
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: mx=0 p=nums[0] for i in range(1,len(nums)): if(nums[i-1]<nums[i]): p+=nums[i] else: mx=max(mx,p) p=nums[i] mx=max(mx,p) return mx
maximum-ascending-subarray-sum
Easy and Optimal Faster
Raghunath_Reddy
0
6
maximum ascending subarray sum
1,800
0.637
Easy
25,758
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/2579931/python3-oror-O(N)-good-solution
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: res = 0 total = 0 nums.append(0) for i in range(len(nums)-1): if nums[i]<nums[i+1]: total+=nums[i] else: res = max(res,total+nums[i]) total = 0 return res
maximum-ascending-subarray-sum
python3 || O(N) good solution
shacid
0
20
maximum ascending subarray sum
1,800
0.637
Easy
25,759
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/2573610/Python-for-beginners
class Solution(object): def maxAscendingSum(self, nums): #Runtime:25ms #Memory Usage:13.4mb total_sum=nums[0] ans=0 for i in range(len(nums)-1): if(nums[i]<nums[i+1]): total_sum+=nums[i+1] else: ans=max(ans,total_sum) total_sum=nums[i+1] return max(ans,total_sum) #Why max is used.. Edge test case:: [In which else part not run in loop i.e. when list given is in sorted order..] #2. [When the last interval of increasing subarray is greater than previous increasing subarrays]
maximum-ascending-subarray-sum
Python for beginners
mehtay037
0
29
maximum ascending subarray sum
1,800
0.637
Easy
25,760
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/2226342/Python-easy-to-understand
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: res = nums[0] curr_max = nums[0] for x in range(1,len(nums)): if nums[x] > nums[x-1]: curr_max += nums[x] res = max(res, curr_max) else: curr_max = nums[x] return res
maximum-ascending-subarray-sum
Python, easy to understand
MacPatil23
0
55
maximum ascending subarray sum
1,800
0.637
Easy
25,761
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/2187462/iterative-current-sum-and-max-sum
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: # iterate every element of nums starting from the top down # iterate up to the second to last index to compare to index ahead # keep track of a current max sum on a new subarray # keep track of the maxSum by using max(), do this everytime the next # value is less than the current value # Time: O(N) Space: O(1) maxSum = max(nums) curr = nums[0] for i in range(len(nums) - 1): if nums[i] < nums[i + 1]: curr += nums[i + 1] else: curr = nums[i + 1] maxSum = max(curr, maxSum) return maxSum
maximum-ascending-subarray-sum
iterative current sum and max sum
andrewnerdimo
0
31
maximum ascending subarray sum
1,800
0.637
Easy
25,762
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1983781/Python3-100-faster-with-explanation
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: currMax, possMax, prev = 0,0, 0 for i in range(len(nums)): if nums[i] <= prev: possMax = 0 prev = nums[i] possMax += nums[i] currMax = max(currMax, possMax) return currMax
maximum-ascending-subarray-sum
Python3 100% faster with explanation
cvelazquez322
0
55
maximum ascending subarray sum
1,800
0.637
Easy
25,763
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1885066/Python3-Simple-Solution-oror-One-pass-oror-Constant-space
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: s,temp = nums[0],nums[0] for i in range(1,len(nums)): if nums[i] > nums[i-1]: temp += nums[i] else: s = max(s,temp) temp = nums[i] return max(s,temp)
maximum-ascending-subarray-sum
[Python3] Simple Solution || One pass || Constant space
abhijeetmallick29
0
33
maximum ascending subarray sum
1,800
0.637
Easy
25,764
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1872889/Python3-O(n)-method-faster-than-99.8
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: maxSum=currSum=last=0 for i in nums: if i<=last: currSum=0 last = i currSum +=i maxSum=max(maxSum,currSum) return maxSum
maximum-ascending-subarray-sum
Python3 O(n) method faster than 99.8%
DanielKao
0
27
maximum ascending subarray sum
1,800
0.637
Easy
25,765
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1859134/Python-dollarolution
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: count = nums[0] m = 0 for i in range(1,len(nums)): if nums[i-1] < nums[i]: count += nums[i] else: m = max(m,count) count = nums[i] m = max(m,count) return m
maximum-ascending-subarray-sum
Python $olution
AakRay
0
28
maximum ascending subarray sum
1,800
0.637
Easy
25,766
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1807864/5-Lines-Python-Solution-oror-95-Faster-(30ms)-oror-Memory-less-than-87
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: ans, i = 0, 0 while i<len(nums)-1: if nums[i]>=nums[i+1]: ans=max(ans,sum(nums[:i+1])) ; nums=nums[i+1:] ; i=-1 i+=1 return max(ans,sum(nums))
maximum-ascending-subarray-sum
5-Lines Python Solution || 95% Faster (30ms) || Memory less than 87%
Taha-C
0
60
maximum ascending subarray sum
1,800
0.637
Easy
25,767
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1511644/One-pass-94-speed
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: ans = sub_sum = 0 for i, n in enumerate(nums): if i == 0: sub_sum = n else: if nums[i - 1] < n: sub_sum += n else: ans = max(ans, sub_sum) sub_sum = n return max(ans, sub_sum)
maximum-ascending-subarray-sum
One pass, 94% speed
EvgenySH
0
74
maximum ascending subarray sum
1,800
0.637
Easy
25,768
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1466674/Python-O(n)-time-O(1)-space-solution-super-easy
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: if len(nums) ==1: return nums[0] n = len(nums) maxsum = nums[0] start, end = 0, 0 while end <= n-1: s = nums[start] while end <= n-2 and nums[end] < nums[end+1]: s += nums[end+1] end += 1 maxsum = max(maxsum, s) start = end + 1 end = start return maxsum
maximum-ascending-subarray-sum
Python O(n) time, O(1) space solution, super easy
byuns9334
0
78
maximum ascending subarray sum
1,800
0.637
Easy
25,769
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1461936/Faster-than-94-oror-28ms-oror-O(n)-oror-O(1)-oror-Python-3
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: # a simple conceptual question #basically once ascending order of subarray ends we take sum all over again for new subarray...and maximum sum so far has to be maintained with it curr_sum = max_sum_so_far = 0 last=nums[0]-1 #update last each time for x in nums: if last<x: curr_sum+=x max_sum_so_far = max(curr_sum,max_sum_so_far) else: curr_sum=x last = x return max_sum_so_far
maximum-ascending-subarray-sum
Faster than 94% || 28ms || O(n) || O(1) || Python 3
ana_2kacer
0
63
maximum ascending subarray sum
1,800
0.637
Easy
25,770
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1427171/WEEB-DOES-PYTHON
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: max_sum, cur_max = nums[0], nums[0] for i in range(1, len(nums)): if nums[i-1] < nums[i]: cur_max += nums[i] max_sum = max(max_sum, cur_max) else: cur_max = nums[i] return max_sum
maximum-ascending-subarray-sum
WEEB DOES PYTHON
Skywalker5423
0
35
maximum ascending subarray sum
1,800
0.637
Easy
25,771
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1407157/Python3-Faster-Than-93.87
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: nums.append(0) mx, i, s = 0, 0, 0 while i < (len(nums) - 1): s += nums[i] if nums[i] >= nums[i + 1]: mx = max(mx, s) s = 0 i += 1 return mx
maximum-ascending-subarray-sum
Python3 Faster Than 93.87%
Hejita
0
66
maximum ascending subarray sum
1,800
0.637
Easy
25,772
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1266594/Easy-Python-Solution(98.60)
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: count=0 m=nums[0] for i in range(len(nums)): if(nums[i]>nums[i-1]): count+=nums[i] m=(m if m>count else count) else: m=(m if m>count else count) count=nums[i] m=(m if m>count else count) return m
maximum-ascending-subarray-sum
Easy Python Solution(98.60%)
Sneh17029
0
119
maximum ascending subarray sum
1,800
0.637
Easy
25,773
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1220863/C%2B%2BJavaPython-Runtime%3A-0-ms-faster-than-100
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: res = 0 _max = 0 for i, x in enumerate(nums): if nums[i] <= nums[i-1]: res = max(res, _max) _max = 0 _max += nums[i] return max(res,_max)
maximum-ascending-subarray-sum
[C++/Java/Python] Runtime: 0 ms, faster than 100%
tranhoangcore
0
64
maximum ascending subarray sum
1,800
0.637
Easy
25,774
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1180811/Python3-Solution-with-Comments-Beats-95-in-Running-Time-98-in-Memory
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: summ=0 #initialize sum as 0 max_summ = 0 #to store the maximum sum start = 0 while start<len(nums)-1: #check if a subarray is ascending if nums[start]<nums[start+1]: #subarray is ascending summ+=nums[start] #update the sum value for this subarray else: #subarray is not ascending max_summ=max(max_summ,summ+nums[start]) #take the maximum between the current maximum and sum of suarray summ=0 #initialize the sum for next subarray start+=1 # print(summ) #the rightmost element of the array is not considered in calculating the sum if nums[start-1]<nums[len(nums)-1]: #the last subarray is still ascending return max(max_summ, summ+nums[len(nums)-1]) #take the maximum between current maximum and sum of last subarray including rightmost element of nums else: #last subarray is not ascending return max(max_summ, summ, nums[len(nums)-1]) #take the maximum between current maximum, current sum and the rightmost element of nums
maximum-ascending-subarray-sum
Python3 Solution with Comments, Beats 95% in Running Time, 98% in Memory
bPapan
0
34
maximum ascending subarray sum
1,800
0.637
Easy
25,775
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1122765/Single-pass-solution-(Kadane's-Algorithm)
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: max_sum = current_sum = prior_num = nums[0] for num in nums[1:]: current_sum = num + (current_sum if num > prior_num else 0) if current_sum > max_sum: max_sum = current_sum prior_num = num return max_sum
maximum-ascending-subarray-sum
Single pass solution (Kadane's Algorithm)
alexanco
0
105
maximum ascending subarray sum
1,800
0.637
Easy
25,776
https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1121117/Python3-Straight-forward-Solution
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: total = 0 max_total = 0 i = 0 while i < len(nums): if nums[i] <= nums[i-1]: total = 0 total += nums[i] max_total = max(total, max_total) i += 1 return max_total
maximum-ascending-subarray-sum
Python3 Straight-forward Solution
cppygod
0
51
maximum ascending subarray sum
1,800
0.637
Easy
25,777
https://leetcode.com/problems/number-of-orders-in-the-backlog/discuss/1119692/Python3-priority-queue
class Solution: def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int: ans = 0 buy, sell = [], [] # max-heap &amp; min-heap for p, q, t in orders: ans += q if t: # sell order while q and buy and -buy[0][0] >= p: # match pb, qb = heappop(buy) ans -= 2*min(q, qb) if q < qb: heappush(buy, (pb, qb-q)) q = 0 else: q -= qb if q: heappush(sell, (p, q)) else: # buy order while q and sell and sell[0][0] <= p: # match ps, qs = heappop(sell) ans -= 2*min(q, qs) if q < qs: heappush(sell, (ps, qs-q)) q = 0 else: q -= qs if q: heappush(buy, (-p, q)) return ans % 1_000_000_007
number-of-orders-in-the-backlog
[Python3] priority queue
ye15
6
596
number of orders in the backlog
1,801
0.474
Medium
25,778
https://leetcode.com/problems/number-of-orders-in-the-backlog/discuss/1119692/Python3-priority-queue
class Solution: def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int: buy, sell = [], [] # max-heap &amp; min-heap for p, q, t in orders: if t: heappush(sell, [p, q]) else: heappush(buy, [-p, q]) while buy and sell and -buy[0][0] >= sell[0][0]: qty = min(buy[0][1], sell[0][1]) buy[0][1] -= qty sell[0][1] -= qty if not buy[0][1]: heappop(buy) if not sell[0][1]: heappop(sell) return (sum(q for _, q in sell) + sum(q for _, q in buy)) % 1_000_000_007
number-of-orders-in-the-backlog
[Python3] priority queue
ye15
6
596
number of orders in the backlog
1,801
0.474
Medium
25,779
https://leetcode.com/problems/number-of-orders-in-the-backlog/discuss/1975718/Python-Concise-Heap-Implementation
class Solution: def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int: # note that: buy_log - max heap; sell_log - min heap buy_log, sell_log = [], [] for price, amount, order_type in orders: target_log = buy_log if order_type else sell_log while amount and target_log: # check that the appropriate buy/sell order fits the criteria # if order type is sell, ensure buy order price >= current price # else if order type is buy, ensure sell order price <= current price if (order_type and abs(target_log[0][0]) < price) or \ (not order_type and target_log[0][0] > price): break current_price, current_amount = heappop(target_log) # cancel buy and sell orders min_amount = min(amount, current_amount) amount -= min_amount current_amount -= min_amount # check if there are remaining target orders if current_amount: heappush(target_log, (current_price, current_amount)) # check if there are remaining current orders if amount: heappush(sell_log if order_type else buy_log, # negate price if order type is buy # so as to maintain a max heap for buy orders (price if order_type else -price, amount)) return (sum(log_amount for _, log_amount in buy_log) + \ sum(log_amount for _, log_amount in sell_log))%int(1e9+7)
number-of-orders-in-the-backlog
[Python] Concise Heap Implementation
zayne-siew
3
202
number of orders in the backlog
1,801
0.474
Medium
25,780
https://leetcode.com/problems/number-of-orders-in-the-backlog/discuss/1975718/Python-Concise-Heap-Implementation
class Solution: def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int: backlog = ([], []) # (buy (max-heap), sell (min-heap)) for price, amount, order_type in orders: # check that the appropriate buy/sell order fits the criteria in the while loop # note that le, ge come from the Python operator library # equivalent to: le - lambda a, b: a <= b # ge - lambda a, b: a >= b while amount > 0 and \ (target_log := backlog[1-order_type]) and \ (le, ge)[order_type](abs(target_log[0][0]), price): curr_price, curr_amount = heappop(target_log) if (amount := amount-curr_amount) < 0: # there are remaining target orders heappush(target_log, (curr_price, -amount)) if amount > 0: # there are remaining current orders heappush(backlog[order_type], (price if order_type else -price, amount)) # note that itemgetter comes from the Python operator library # equivalent to: lambda t: t[1] return sum(sum(map(itemgetter(1), log)) for log in backlog)%int(1e9+7)
number-of-orders-in-the-backlog
[Python] Concise Heap Implementation
zayne-siew
3
202
number of orders in the backlog
1,801
0.474
Medium
25,781
https://leetcode.com/problems/number-of-orders-in-the-backlog/discuss/1346115/Two-heaps-76-speed
class Solution: def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int: buy_log = [] sell_log = [] for price, amount, order_type in orders: if order_type: while buy_log and amount: buy_price, buy_amount = heappop(buy_log) if -buy_price >= price: if buy_amount <= amount: amount -= buy_amount else: buy_amount -= amount heappush(buy_log, (buy_price, buy_amount)) amount = 0 else: heappush(buy_log, (buy_price, buy_amount)) break if amount: heappush(sell_log, (price, amount)) else: while sell_log and amount: sell_price, sell_amount = heappop(sell_log) if sell_price <= price: if sell_amount <= amount: amount -= sell_amount else: sell_amount -= amount heappush(sell_log, (sell_price, sell_amount)) amount = 0 else: heappush(sell_log, (sell_price, sell_amount)) break if amount: heappush(buy_log, (-price, amount)) return (sum(amount for _, amount in buy_log) + sum(amount for _, amount in sell_log)) % 1_000_000_007
number-of-orders-in-the-backlog
Two heaps, 76% speed
EvgenySH
0
117
number of orders in the backlog
1,801
0.474
Medium
25,782
https://leetcode.com/problems/number-of-orders-in-the-backlog/discuss/1119729/Easy-to-understand-python-solution
class Solution: def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int: backlog = defaultdict(list) for price, amount, ordertype in orders: #sell if ordertype == 1: if backlog[0]: condition = True while condition and backlog[0]: bp, ba = heapq.heappop(backlog[0]) if -bp >= price: if amount < ba: ba -= amount amount = 0 heapq.heappush(backlog[0], [bp, ba]) condition = False elif amount > ba: amount -=ba else: amount = 0 else: heapq.heappush(backlog[0], [bp,ba]) heapq.heappush(backlog[1], [price, amount]) amount = 0 condition = False if amount: heapq.heappush(backlog[1], [price, amount]) else: heapq.heappush(backlog[1], [price, amount]) #buy if ordertype == 0: if backlog[1]: condition = True while condition and backlog[1]: sp, sa = heapq.heappop(backlog[1]) if sp <= price: if amount < sa: sa -= amount amount = 0 heapq.heappush(backlog[1], [sp, sa]) condition = False elif amount > sa: amount -=sa else: amount = 0 else: heapq.heappush(backlog[1], [sp, sa]) heapq.heappush(backlog[0], [-price, amount]) amount = 0 condition = False if amount: heapq.heappush(backlog[0], [-price, amount]) else: heapq.heappush(backlog[0], [-price, amount]) #print(backlog[0], backlog[1]) res = 0 for i,j in backlog[0]: res += j for i,j in backlog[1]: res += j return res % (10**9 + 7)
number-of-orders-in-the-backlog
Easy to understand python solution
deleted_user
0
67
number of orders in the backlog
1,801
0.474
Medium
25,783
https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/discuss/1119650/Growing-A-HillPyramid-with-Visualization-in-Python3
class Solution: def maxValue(self, n: int, index: int, maxSum: int) -> int: res_i, crr_sum = 0, n l, r, w_hill = index + 1, index - 1, 1 # left/right indices and width of the hill while crr_sum <= maxSum: l -= 1 r += 1 if l == index and r == index: crr_sum += w_hill else: l_, r_ = max(l, 0), min(r, n - 1) ''' when the hill has the same width as the ground, simply just speed up growing by adding the result of dividing (maxSum - crr_sum) by w_hill ''' if l < l_ and r > r_: rm = maxSum - crr_sum res_i += int(rm / w_hill) + 1 break else: w_hill = r_ - l_ + 1 crr_sum += w_hill res_i += 1 return res_i
maximum-value-at-a-given-index-in-a-bounded-array
Growing A [Hill/Pyramid] with Visualization in [Python3]
BryanBoCao
5
396
maximum value at a given index in a bounded array
1,802
0.319
Medium
25,784
https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/discuss/1119696/Python3-binary-search
class Solution: def maxValue(self, n: int, index: int, maxSum: int) -> int: def fn(n, x): if n < x: return n*(2*x-n+1)//2 return x*(1+x)//2 + n - x # last true binary search lo, hi = 0, maxSum while lo < hi: mid = lo + hi + 1 >> 1 sm = fn(index, mid-1) + fn(n-index, mid) if sm <= maxSum: lo = mid else: hi = mid - 1 return lo
maximum-value-at-a-given-index-in-a-bounded-array
[Python3] binary search
ye15
3
212
maximum value at a given index in a bounded array
1,802
0.319
Medium
25,785
https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/discuss/2748799/Binary-search-on-possible-heights.-O(log(m))
class Solution: def maxValue(self, n: int, index: int, maxSum: int) -> int: maxSum -= n def check(h): a = max(h - index, 0) b = max(h - (n - 1 - index), 0) return (h - 1 + a)*(h - 1 - a + 1)/2 + (h + b)*(h - b + 1)/2 left, right = 1, maxSum + 1 while left < right: mid = (left + right) // 2 if check(mid) > maxSum: right = mid else: left = mid + 1 return right
maximum-value-at-a-given-index-in-a-bounded-array
Binary search on possible heights. O(log(m))
nonchalant-enthusiast
0
10
maximum value at a given index in a bounded array
1,802
0.319
Medium
25,786
https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/discuss/1347327/Binary-search-84-speed
class Solution: @classmethod def min_area(cls, len_arr, idx, target): if target + idx >= len_arr: sum_r = (2 * target - len_arr + idx) * (len_arr - 1 - idx) // 2 else: sum_r = target * (target - 1) // 2 + len_arr - idx - target if target - idx >= 1: sum_l = (2 * target - 1 - idx) * idx // 2 else: sum_l = target * (target - 1) // 2 + idx - target + 1 return sum_l + sum_r + target def maxValue(self, n: int, index: int, maxSum: int) -> int: left, right = 1, maxSum - n + 2 while left + 1 < right: middle = (left + right) // 2 if Solution.min_area(n, index, middle) <= maxSum: left = middle else: right = middle return left
maximum-value-at-a-given-index-in-a-bounded-array
Binary search, 84% speed
EvgenySH
0
125
maximum value at a given index in a bounded array
1,802
0.319
Medium
25,787
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1491046/Python-3-Short-and-easy-to-understand
class Solution: def numDifferentIntegers(self, word: str) -> int: word = re.findall('(\d+)', word) numbers = [int(i) for i in word] return len(set(numbers))
number-of-different-integers-in-a-string
Python 3 Short and easy to understand
frolovdmn
5
313
number of different integers in a string
1,805
0.362
Easy
25,788
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1130755/Python3-groupby
class Solution: def numDifferentIntegers(self, word: str) -> int: seen = set() for key, grp in groupby(word, str.isdigit): if key: seen.add(int("".join(grp))) return len(seen)
number-of-different-integers-in-a-string
[Python3] groupby
ye15
4
176
number of different integers in a string
1,805
0.362
Easy
25,789
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1545654/Very-easy-and-straightfoward-O(n)-solution
class Solution: def numDifferentIntegers(self, word: str) -> int: out = '' #Replace every non digits by spaces for char in word: if char.isdigit(): out = out + char else: out = out + ' ' #Cleaning up None characters (double spaces) and converting digits from str to int out = out.split(' ') out_ = [] for number in out: if number != '': out_.append(int(number)) #Using set() for filtering out repeat numbers return len(set(out_))
number-of-different-integers-in-a-string
Very easy and straightfoward O(n) solution
Sima24
3
273
number of different integers in a string
1,805
0.362
Easy
25,790
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1201024/python3-one-line-regex
class Solution: def numDifferentIntegers(self, word: str) -> int: return len(set(map(int, re.findall('\d+', word))))
number-of-different-integers-in-a-string
python3 one-line regex
Hoke_luo
2
109
number of different integers in a string
1,805
0.362
Easy
25,791
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1134301/python-faster-than-100-(20ms)
class Solution: def numDifferentIntegers(self, word: str) -> int: parsed = [] for c in word: if c.isalpha(): parsed.append(" ") else: parsed.append(c) parsed = ("".join(parsed)).split(" ") parsed = [int(c) for c in parsed if c] return len(set(parsed)) ''' Time: O(n) Space: O(n) '''
number-of-different-integers-in-a-string
python faster than 100% (20ms)
uzumaki01
1
282
number of different integers in a string
1,805
0.362
Easy
25,792
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1131156/Python-oror-Easy-O(N)
class Solution: def numDifferentIntegers(self, word: str) -> int: prev = word[0] if word[0].isdigit() else "" # if 1st char is digit or not seen = set() # to store different numbers for i in range(1, len(word)): if word[i].isdigit() and word[i-1].isdigit(): # if previous char was also a digit prev += word[i] continue if word[i].isdigit(): # new number found if prev: # add prev number to seen if any seen.add(int(prev)) prev = "" # to store new number prev += word[i] if prev: seen.add(int(prev)) # add last number to seen if any return len(seen)
number-of-different-integers-in-a-string
Python || Easy O(N)
airksh
1
71
number of different integers in a string
1,805
0.362
Easy
25,793
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2827983/Python-3-liners%3A-re.split-and-filter-and-map-and-set
class Solution: def numDifferentIntegers(self, word: str) -> int: arr = re.split('\D+', word) arr = set(map(int, filter(None, arr))) return len(arr)
number-of-different-integers-in-a-string
Python 3 liners: re.split & filter & map & set
StacyAceIt
0
2
number of different integers in a string
1,805
0.362
Easy
25,794
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2753943/Python-faster-than-90-memory-less-than-97
class Solution: def numDifferentIntegers(self, word: str) -> int: digits = set() idx = 0 while idx < len(word): digit = "" while idx < len(word) and word[idx].isnumeric(): digit += word[idx] idx += 1 if digit: digits.add(int(digit)) idx += 1 return len(digits)
number-of-different-integers-in-a-string
[Python] faster than 90% memory less than 97%
javiermora
0
20
number of different integers in a string
1,805
0.362
Easy
25,795
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2743009/Python3-Sliding-window
class Solution: def numDifferentIntegers(self, word: str) -> int: last = 0 numbers = set() for idx, char in enumerate(word): if not char.isdigit(): if idx > last: numbers.add(int(word[last:idx])) last = idx+1 # account for the last digits if last < len(word): numbers.add(int(word[last:])) return len(numbers)
number-of-different-integers-in-a-string
[Python3] - Sliding window
Lucew
0
4
number of different integers in a string
1,805
0.362
Easy
25,796
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2707895/python-easy-solution-without-regex
class Solution: def numDifferentIntegers(self, word: str) -> int: word=word+'x' res=set() p="" for i in ((word)): if(i.isdigit()): p+=i else: if(p not in res and p!=""): res.add(int(p)) p="" return len(res)
number-of-different-integers-in-a-string
python easy solution without regex
Raghunath_Reddy
0
4
number of different integers in a string
1,805
0.362
Easy
25,797
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2601003/python-or-explanation-in-comments
class Solution: def numDifferentIntegers(self, word: str) -> int: res = set() integer = "" for i in range(len(word)): # append to 'integer' only if it's a digit if word[i].isdigit(): integer += word[i] else: if integer: # convert to actual integer before resetting (this ensures tackling 0's at the beginning) res.add(int(integer)) integer = "" if integer: res.add(int(integer)) return len(res)
number-of-different-integers-in-a-string
python | explanation in comments
sproq
0
21
number of different integers in a string
1,805
0.362
Easy
25,798
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2420318/Easy-Python-Solution-(-Short-)
class Solution: def numDifferentIntegers(self, word: str) -> int: rw,r = ' ','' for i in word: if i.isdigit(): r += i else: r += rw return len(set(map(int, r.split())))
number-of-different-integers-in-a-string
Easy Python Solution ( Short )
SouravSingh49
0
45
number of different integers in a string
1,805
0.362
Easy
25,799