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/apply-operations-to-an-array/discuss/2783161/Python3-solved-in-place | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
zeros=0
nums+=[0]
for i in range(len(nums)-1):
if nums[i]==0:
zeros+=1
elif nums[i]==nums[i+1]:
nums[i-zeros]=nums[i]*2
nums[i+1]=0
else:
nums[i-zeros]=nums[i]
return nums[:len(nums)-1-zeros] + [0]*zeros | apply-operations-to-an-array | Python3, solved in place | Silvia42 | 1 | 94 | apply operations to an array | 2,460 | 0.671 | Easy | 33,700 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2845376/Python3-Inplace-Operations-Linear-Time-Constant-Space | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
#apply the operations
for idx, num in enumerate(nums[1:]):
if nums[idx] == num:
nums[idx] *= 2
nums[idx+1] = 0
# find the first zero
for first_zero, num in enumerate(nums):
if not num: break
# check if there are any to shift
if first_zero == len(nums) - 1: return nums
# go through the array and shift numbers to the left
for idx, num in enumerate(nums[first_zero+1:], first_zero+1):
# we found a valid number after the zero so we need to switch it
if num:
nums[first_zero] = num
nums[idx] = 0
# go further with our first zero counter
while first_zero < len(nums) and nums[first_zero]:
first_zero += 1
# check if we went out of bounds
if first_zero > len(nums) - 1: break
return nums | apply-operations-to-an-array | [Python3] - Inplace Operations - Linear Time - Constant Space | Lucew | 0 | 3 | apply operations to an array | 2,460 | 0.671 | Easy | 33,701 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2820653/While-loop-beats-96.68-memory-usage | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
i = 0
while i < len(nums) - 1:
if nums[i] != nums[i + 1]:
i += 1
else:
nums[i] *= 2
nums[i + 1] = 0
i += 1
return [x for x in nums if x] + [0]*nums.count(0) | apply-operations-to-an-array | While loop beats 96.68% memory usage | Molot84 | 0 | 4 | apply operations to an array | 2,460 | 0.671 | Easy | 33,702 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2817460/python-or-fastor-readable | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
zeros = []
for i in range(len(nums) - 1):
if nums[i] == 0:
zeros.append(i)
if nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
for i, j in enumerate(zeros):
nums.append(nums.pop((j-i)))
return nums | apply-operations-to-an-array | python | fast| readable | IAMdkk | 0 | 3 | apply operations to an array | 2,460 | 0.671 | Easy | 33,703 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2816038/Slow-but-simple-Counter-and-loops | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
#start i at 0
i=0
#as per question, it's n-1 operations
while i < (len(nums)-1):
#again, they told us this line in the question
if nums[i] == nums[i+1]:
#following the instructions
nums[i] *= 2
#again, the instuctions say this
nums[i+1] *= 0
#increment i by 1
i+=1
#use counter on the list
_c = Counter(nums)
#find the number of zeroes
_z = _c[0]
#loop once for eacj zero in the list
for k in range(_z):
#remove a zero
nums.remove(0)
#append it to the end
nums.append(0)
#then we can return nums
return nums | apply-operations-to-an-array | Slow but simple - Counter and loops | ATHBuys | 0 | 2 | apply operations to an array | 2,460 | 0.671 | Easy | 33,704 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2815383/Python-basic-solution-with-one-loop | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
end = len(nums)
j = 0
for i in range(end):
if i < end - 1 and nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
if nums[i] != 0:
if i != j:
nums[i], nums[j] = nums[j], nums[i]
j += 1
return nums | apply-operations-to-an-array | Python, basic solution with one loop | user9154Sr | 0 | 4 | apply operations to an array | 2,460 | 0.671 | Easy | 33,705 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2815030/python-Easy-Solution | class Solution(object):
def applyOperations(self, nums):
ns=len(nums)
for i in range ( len(nums)-1):
if nums[i] == nums[i+1]:
nums[i] *=2
nums[i+1] = 0
return sorted(nums, key=lambda x: not x) | apply-operations-to-an-array | python Easy Solution | mohammed-ishaq | 0 | 5 | apply operations to an array | 2,460 | 0.671 | Easy | 33,706 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2812020/Python-O(n)-time | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
return [x for x in nums if x] + [x for x in nums if not x] | apply-operations-to-an-array | [Python] O(n) time | javiermora | 0 | 7 | apply operations to an array | 2,460 | 0.671 | Easy | 33,707 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2807915/Very-simple-python-solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
length = len(nums)
for i in range(0, length-1):
if nums[i]==nums[i+1]:
nums[i] = nums[i]*2
nums[i+1] = 0
res = sorted(nums, key=lambda x: x == 0)
return res | apply-operations-to-an-array | Very simple python solution | fzhurd | 0 | 4 | apply operations to an array | 2,460 | 0.671 | Easy | 33,708 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2805306/Python-solution-that-beats-95-users-and-saves-space | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n = len(nums)
for i in range(n-1) :
if nums[i] == nums[i+1] :
nums[i] *= 2
nums[i+1] = 0
count = nums.count(0)
q = 0
while q < len(nums) :
if nums[q] == 0 :
nums.pop(q)
else :
q += 1
nums += [0]*count
return nums | apply-operations-to-an-array | Python solution that beats 95% users and saves space | bhavithas153 | 0 | 5 | apply operations to an array | 2,460 | 0.671 | Easy | 33,709 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2803706/Different-Approaches-Optimized | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n = len(nums)
a,c = [],0
for i in range(n-1):
if nums[i]>0 and nums[i]==nums[i+1]:
a.append(nums[i]*2)
nums[i+1]=0
elif nums[i]!=0:
a.append(nums[i])
else:
c+=1
if nums[-1]!=0:
a.append(nums[-1])
else:
c+=1
a.extend([0]*(c))
return a | apply-operations-to-an-array | Different Approaches , Optimized | Rtriders | 0 | 4 | apply operations to an array | 2,460 | 0.671 | Easy | 33,710 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2802429/Python-Solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
l1=[]
l2=[]
for i in range(len(nums)-1):
if(nums[i]==0):
l2.append(0)
elif(nums[i]==nums[i+1]):
l1.append(nums[i]*2)
nums[i+1]=0
else:
l1.append(nums[i])
if(nums[len(nums)-1]==0):
l2.append(0)
else:
l1.append(nums[-1])
return l1+l2 | apply-operations-to-an-array | Python Solution | CEOSRICHARAN | 0 | 3 | apply operations to an array | 2,460 | 0.671 | Easy | 33,711 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2801193/Python-3-%3A-O(n)-time-complexity-O(1)-space-complexity | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
nums[i]=nums[i]*2
nums[i+1]=0
k=0
for i in range(len(nums)):
if (nums[i]==0):
continue
else:
nums[k]=nums[i]
k+=1
for i in range(k,len(nums)):
nums[i]=0
return nums | apply-operations-to-an-array | Python 3 : O(n) time complexity O(1) space complexity | CharuArora_ | 0 | 4 | apply operations to an array | 2,460 | 0.671 | Easy | 33,712 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2801192/Python-3-%3A-O(n)-time-complexity-O(1)-space-complexity | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
nums[i]=nums[i]*2
nums[i+1]=0
k=0
for i in range(len(nums)):
if (nums[i]==0):
continue
else:
nums[k]=nums[i]
k+=1
for i in range(k,len(nums)):
nums[i]=0
return nums | apply-operations-to-an-array | Python 3 : O(n) time complexity O(1) space complexity | CharuArora_ | 0 | 2 | apply operations to an array | 2,460 | 0.671 | Easy | 33,713 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2797409/Basic-easy-python-solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(0 , len(nums) - 1):
if nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
zeros = 0
non_zero = []
for i in nums:
if i == 0:
zeros += 1
else:
non_zero.append(i)
return non_zero + [0]*zeros | apply-operations-to-an-array | Basic easy python solution | akashp2001 | 0 | 4 | apply operations to an array | 2,460 | 0.671 | Easy | 33,714 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2792517/One-Pass-Optimal-Solution-oror-O(N)-oror-O(1) | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n = len(nums)
ptr = 0
for i in range(n):
if nums[i] == 0: # Skip if number in array is 0
#no operations required
continue
elif i < n-1 and nums[i] == nums[i+1] : # if numbers are equal
#double
tmp = nums[i] << 1
#swap nums[ptr] and nums[i]
nums[i], nums[i+1] = 0, 0
nums[ptr] = tmp
#increment ptr
ptr+=1
else: # if number is a non-zero
#swap nums[ptr] and nums[i]
tmp, nums[i] = nums[i], 0
nums[ptr] = tmp
#increment ptr
ptr+=1
return nums | apply-operations-to-an-array | ✅ One Pass Optimal Solution || O(N) || O(1) | henriducard | 0 | 23 | apply operations to an array | 2,460 | 0.671 | Easy | 33,715 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2791760/Simple-Brute-Force-O(n)-Solution-Easy-No-Tricks-or-Python | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
zeros = []
others = []
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
if nums[i] == 0:
zeros.append(0)
else:
others.append(nums[i])
if i == len(nums)-2:
# for the last one
if nums[-1] == 0:
zeros.append(0)
else:
others.append(nums[-1])
return others+zeros | apply-operations-to-an-array | Simple Brute Force O(n) Solution Easy No Tricks | Python | chienhsiang-hung | 0 | 13 | apply operations to an array | 2,460 | 0.671 | Easy | 33,716 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2791314/Simple-two-pointer-python-solution-no-zero-sorting | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
i = j = 0
while j < len(nums):
if nums[j]:
if j+1 < len(nums) and nums[j] == nums[j+1]:
nums[i] = nums[j] * 2
j+=1
i+=1
else:
nums[i] = nums[j]
i+=1
j+=1
# fill remaining with zeros
for k in range(i,j):
nums[k] = 0
return nums | apply-operations-to-an-array | Simple two pointer python solution, no zero sorting | stereo1 | 0 | 6 | apply operations to an array | 2,460 | 0.671 | Easy | 33,717 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2787224/Python-Super-Easy-Naive-Solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
count = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[count], nums[i] = nums[i], nums[count]
count += 1
return nums | apply-operations-to-an-array | Python Super Easy Naive Solution | kaien | 0 | 7 | apply operations to an array | 2,460 | 0.671 | Easy | 33,718 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2786514/Python3-O(n)-solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
# input: 0-indexed array with integers >= 0
# output: array with integers with last elements = 0
# e.g.: [1, 2, 2, 1, 1, 0]
# [1, 4, 0, 2, 0, 0] ->
# for loop: if el != 0 -> continue, elif el == 0 -> swap el with el + 1
# loop goes from len - 2 -> 0
# operations: if i = i+1 -> *2 i, 0 for i + 1, else continue
output = []
track = 0
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
if nums[i + 1] == 0 and i + 1 == len(nums) - 1:
track += 1
if nums[i] == 0:
track += 1
# [1, 0, 4, 2, 0, 0]
for i in range(len(nums)):
if nums[i] != 0:
output.append(nums[i])
return output + [0] * track | apply-operations-to-an-array | [Python3] O(n) solution | phucnguyen290198 | 0 | 8 | apply operations to an array | 2,460 | 0.671 | Easy | 33,719 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2786458/Simple-step-by-step | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
i=0
res=[]
while i< len(nums)-1:
if nums[i]== nums[i+1]:
res.append(nums[i]*2)
res.append(0)
i=i+2
else:
res.append(nums[i])
i=i+1
if i == len(nums)-1:
res.append(nums[-1])
return sorted(res, key=lambda x: not x) | apply-operations-to-an-array | Simple step by step | Antarab | 0 | 3 | apply operations to an array | 2,460 | 0.671 | Easy | 33,720 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2786273/Python-single-pass | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
w = 0
for i in range(len(nums)):
if i < len(nums) - 1 and nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
if nums[i] != 0:
nums[w] = nums[i]
w += 1
nums[w:] = [0] * (len(nums) - w)
return nums | apply-operations-to-an-array | Python, single pass | blue_sky5 | 0 | 2 | apply operations to an array | 2,460 | 0.671 | Easy | 33,721 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2786251/Python-or-1-Pass-or-O(n)-time-O(1)-space | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
curr_idx = 0
for i, num in enumerate(nums):
if i < len(nums) - 1 and num == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
if nums[i]:
nums[curr_idx] = nums[i]
curr_idx += 1
for i in range(curr_idx, len(nums)):
nums[i] = 0
return nums | apply-operations-to-an-array | Python | 1 Pass | O(n) time O(1) space | leeteatsleep | 0 | 6 | apply operations to an array | 2,460 | 0.671 | Easy | 33,722 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2786019/Python-(Simple-Maths) | class Solution:
def dfs(self,ans):
for i in range(1,len(ans)):
if ans[i] == ans[i-1]:
ans[i] = 0
ans[i-1] = 2*ans[i-1]
return ans
def bfs(self,res):
res1, res2 = [], []
for i in res:
if i != 0:
res1.append(i)
else:
res2.append(i)
return res1 + res2
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
nums = self.dfs(nums)
return self.bfs(nums) | apply-operations-to-an-array | Python (Simple Maths) | rnotappl | 0 | 7 | apply operations to an array | 2,460 | 0.671 | Easy | 33,723 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2785592/Python3-Generate-New-Array | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
i, j, e, na = 0, 0, len(nums) - 1, [0 for i in range(len(nums))]
while i < e:
c = nums[i]
if c:
if c == nums[i+1]:
c += c
i += 1
na[j] = c
j += 1
i += 1
if i == e:
na[j]=nums[i]
return na | apply-operations-to-an-array | Python3 Generate New Array | godshiva | 0 | 5 | apply operations to an array | 2,460 | 0.671 | Easy | 33,724 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2785408/Python | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
res = []
for i in nums:
if i:
res.append(i)
while len(res) != len(nums):
res.append(0)
return res | apply-operations-to-an-array | Python | JSTM2022 | 0 | 3 | apply operations to an array | 2,460 | 0.671 | Easy | 33,725 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2785278/Python-solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
nums[i]=nums[i]*2
nums[i+1]=0
else:
continue
j1=0
for i in range(len(nums)):
if nums[i]!=0:
nums[j1],nums[i]=nums[i],nums[j1]
j1+=1
return nums | apply-operations-to-an-array | Python solution | shashank_2000 | 0 | 10 | apply operations to an array | 2,460 | 0.671 | Easy | 33,726 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2784689/Python3-oror-Simple-solution-oror-List-comprehension | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for ix in range(len(nums)-1):
if nums[ix] == nums[ix+1]:
nums[ix] *= 2
nums[ix+1] = 0
new_list = [n for n in nums if n != 0] + [n for n in nums if n == 0]
return new_list | apply-operations-to-an-array | Python3 || Simple solution || List comprehension | YLW_SE | 0 | 6 | apply operations to an array | 2,460 | 0.671 | Easy | 33,727 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2784645/Python-or-Simulation-%2B-Two-Pointers | class Solution:
def applyOperations(self, xs: List[int]) -> List[int]:
n = len(xs)
for i in range(n-1):
if xs[i] == xs[i+1]:
xs[i] *= 2
xs[i+1] = 0
# Now move 0's to the end of the array.
i = 0
# Find first zero (if any).
while i < n and xs[i] != 0:
i += 1
if i == n:
return xs
# The variable i points to the first zero.
j = i + 1
while j < n:
if xs[j] != 0:
xs[i], xs[j] = xs[j], xs[i]
i += 1
j += 1
return xs | apply-operations-to-an-array | Python | Simulation + Two Pointers | on_danse_encore_on_rit_encore | 0 | 4 | apply operations to an array | 2,460 | 0.671 | Easy | 33,728 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2784548/Stack-for-non-zero-elements-100-speed | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
stack, n = [], len(nums)
n1, i = n - 1, 0
while i < n:
if nums[i] > 0:
if i == n1:
stack.append(nums[i])
break
elif nums[i] == nums[i + 1]:
stack.append(nums[i] * 2)
i += 2
continue
else:
stack.append(nums[i])
i += 1
return stack + [0] * (n - len(stack)) | apply-operations-to-an-array | Stack for non-zero elements, 100% speed | EvgenySH | 0 | 5 | apply operations to an array | 2,460 | 0.671 | Easy | 33,729 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2784247/Python-brute-force | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
nums[i]=2*nums[i]
nums[i+1]=0
return list(filter(lambda x: x!=0, nums))+[0]*nums.count(0) | apply-operations-to-an-array | Python, brute force | Leox2022 | 0 | 4 | apply operations to an array | 2,460 | 0.671 | Easy | 33,730 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2784081/Python-Solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
l = []
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
nums[i] = nums[i] * 2
nums[i + 1] = 0
j = 0
for i in range(len(nums)):
if nums[i] == 0:
l.append(0)
else:
l.insert(j,nums[i])
j += 1
return l | apply-operations-to-an-array | Python Solution | a_dityamishra | 0 | 5 | apply operations to an array | 2,460 | 0.671 | Easy | 33,731 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783945/O(n)-approach-simple | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
l=0
r=1
c=0
zerolist=[]
while r < len(nums):
if nums[l] == nums[r]:
nums[l]=nums[l]*2
nums[r] = 0
l+=1
r+=1
else:
l+=1
r+=1
for i in nums:
if i == 0:
zerolist.append(i)
res = [i for i in nums if i != 0]
return(res+zerolist) | apply-operations-to-an-array | O(n) approach simple | guptatanish318 | 0 | 6 | apply operations to an array | 2,460 | 0.671 | Easy | 33,732 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783936/Two-pointer-Solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
nums[i] = 2*nums[i]
nums[i+1] = 0
start = 0
end = 1
while end <len(nums):
if nums[start] == 0:
if nums[end] != 0:
nums[start],nums[end] = nums[end],nums[start]
start += 1
end += 1
else:
end += 1
else:
start += 1
end += 1
return nums | apply-operations-to-an-array | Two pointer Solution | kunduruabhinayreddy43 | 0 | 8 | apply operations to an array | 2,460 | 0.671 | Easy | 33,733 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783816/Simple-and-easy-python-approach. | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
nums[i]=nums[i]*2
nums[i+1]=0
count=0
for i in range(len(nums)):
if nums[i]!=0:
nums[count]= nums[i]
count+=1
while count <len(nums):
nums[count]=0
count+=1
return nums | apply-operations-to-an-array | Simple and easy python approach. | numaan1905050100045 | 0 | 9 | apply operations to an array | 2,460 | 0.671 | Easy | 33,734 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783608/Python3-or-Simple | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
first = []
last = []
for i in range(len(nums)):
if i+1 < len(nums) and nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
if nums[i] != 0:
first.append(nums[i])
else:
last.append(nums[i])
return first + last | apply-operations-to-an-array | Python3 | Simple | vikinam97 | 0 | 14 | apply operations to an array | 2,460 | 0.671 | Easy | 33,735 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783579/Beats-100-beginner-friendly... | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
nums[i] = nums[i]*2
nums[i+1] = 0
for i in nums:
if i == 0:
nums.remove(i)
nums.append(i)
return nums | apply-operations-to-an-array | Beats 100%, beginner friendly... | karanvirsagar98 | 0 | 10 | apply operations to an array | 2,460 | 0.671 | Easy | 33,736 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783487/Python-Answer-Filter-and-Count-O's | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
#res = [0] * len(nums)
for i,n in enumerate(nums):
if i < len(nums)-1:
if nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
#else:
return list(filter(lambda x: x > 0, nums)) + [0] * nums.count(0) | apply-operations-to-an-array | [Python Answer🤫🐍🐍🐍] Filter and Count O's | xmky | 0 | 9 | apply operations to an array | 2,460 | 0.671 | Easy | 33,737 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783404/Easy-Python-Soln | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n=len(nums)
for i in range(n-1):
if nums[i]==nums[i+1]:
nums[i]*=2
nums[i+1]=0
j = 0
for i in range(n):
if nums[i] != 0:
nums[j], nums[i] = nums[i], nums[j]
j += 1
return nums | apply-operations-to-an-array | Easy Python Soln | nidhisinghwgs | 0 | 10 | apply operations to an array | 2,460 | 0.671 | Easy | 33,738 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783345/Python-Simple-Straightforward-Brute-force-Solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
return sorted(nums, key=lambda n: not n) | apply-operations-to-an-array | [Python] Simple Straightforward Brute-force Solution | andy2167565 | 0 | 14 | apply operations to an array | 2,460 | 0.671 | Easy | 33,739 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783285/Easy-Python3-Solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
N=len(nums)
for i in range(N-1):
if nums[i]==nums[i+1]:
nums[i]*=2
nums[i+1]=0
r=list(x for x in nums if x!=0)
while len(r)<N:
r.append(0)
return r | apply-operations-to-an-array | Easy Python3 Solution | Motaharozzaman1996 | 0 | 11 | apply operations to an array | 2,460 | 0.671 | Easy | 33,740 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783268/Python-solution-(brute-force) | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n = len(nums)
for i in range(n-1):
if nums[i] == nums[i+1]:
nums[i]*=2
nums[i+1] = 0
res = [0]*n
idx = 0
for num in nums:
if num!=0:
res[idx] = num
idx+=1
return res | apply-operations-to-an-array | Python solution (brute force) | dhanu084 | 0 | 10 | apply operations to an array | 2,460 | 0.671 | Easy | 33,741 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783214/pythonjava-solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
j = 0
i = 0
while j < len(nums) and i < len(nums):
if nums[j] == 0:
j += 1
elif nums[i] != 0:
i += 1
elif nums[j] != 0 and nums[i] == 0:
if j > i:
nums[i], nums[j] = nums[j], nums[i]
else:
j += 1
return nums
class Solution {
public int[] applyOperations(int[] nums) {
for (int i = 0; i < nums.length - 1; i ++) {
if (nums[i] == nums[i + 1]) {
nums[i] *= 2;
nums[i + 1] = 0;
}
}
int i = 0;
int j = 0;
while (i < nums.length && j < nums.length) {
if (nums[j] == 0) {
j ++;
} else if (nums[i] != 0) {
i ++;
} else if (nums[j] != 0 && nums[i] == 0) {
if (j > i) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
} else {
j ++;
}
}
}
return nums;
}
} | apply-operations-to-an-array | python/java solution | akaghosting | 0 | 12 | apply operations to an array | 2,460 | 0.671 | Easy | 33,742 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783213/Simple-python-solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
## RC ##
## APPROACH : ARRAY ##
res = [0] * len(nums)
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
j = 0
for i in range(len(nums)):
if nums[i] != 0:
res[j] = nums[i]
j += 1
return res | apply-operations-to-an-array | Simple python solution | 101leetcode | 0 | 13 | apply operations to an array | 2,460 | 0.671 | Easy | 33,743 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783189/Python-Simple-Python-Solution | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for index in range(len(nums)-1):
if nums[index] == nums[index + 1]:
nums[index] = nums[index] * 2
nums[index + 1] = 0
result = []
count_zero = 0
for num in nums:
if num != 0:
result.append(num)
else:
count_zero = count_zero + 1
result = result + [0] * count_zero
return result | apply-operations-to-an-array | [ Python ] ✅✅ Simple Python Solution 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 37 | apply operations to an array | 2,460 | 0.671 | Easy | 33,744 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783155/Short-and-fast-solution-in-leetcode-history | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
arr=[0]*(len(nums))
l=0
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
nums[i]=nums[i]*2
nums[i+1] = 0
for i,a in enumerate(nums):
if a != 0:
arr[l]=nums[i]
l+=1
return arr | apply-operations-to-an-array | Short and fast solution in leetcode history | parthjain9925 | 0 | 29 | apply operations to an array | 2,460 | 0.671 | Easy | 33,745 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783104/Two-pointers | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n = len(nums)
for i in range(n - 1):
if nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
i = 0
for j in range(n):
if nums[j] != 0:
nums[i] = nums[j]
i += 1
for j in range(i, n):
nums[j] = 0
return nums | apply-operations-to-an-array | Two pointers | theabbie | 0 | 31 | apply operations to an array | 2,460 | 0.671 | Easy | 33,746 |
https://leetcode.com/problems/apply-operations-to-an-array/discuss/2783103/Python3-simulation | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
ans = []
for i, x in enumerate(nums):
if i+1 < len(nums) and nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
if nums[i]: ans.append(nums[i])
return ans + [0]*(len(nums)-len(ans)) | apply-operations-to-an-array | [Python3] simulation | ye15 | 0 | 34 | apply operations to an array | 2,460 | 0.671 | Easy | 33,747 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783646/Python-easy-solution-using-libraries | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
seen = collections.Counter(nums[:k]) #from collections import Counter (elements and their respective count are stored as a dictionary)
summ = sum(nums[:k])
res = 0
if len(seen) == k:
res = summ
for i in range(k, len(nums)):
summ += nums[i] - nums[i-k]
seen[nums[i]] += 1
seen[nums[i-k]] -= 1
if seen[nums[i-k]] == 0:
del seen[nums[i-k]]
if len(seen) == k:
res = max(res, summ)
return res | maximum-sum-of-distinct-subarrays-with-length-k | ✅✅Python easy solution using libraries | Sumit6258 | 4 | 224 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,748 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783468/Sliding-window-with-updates.-100-50 | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
window = Counter(nums[:k])
size = len(window)
n = len(nums)
running = sum(nums[:k])
max_total = running if size == k else 0
for i in range(k, n):
out, v = nums[i-k], nums[i]
window[out] -= 1
if window[out] == 0:
window.pop(out)
size -= 1
if v in window:
window[v] += 1
else:
window[v] = 1
size += 1
running = running + v - out
#print(f"{i}: {nums[i]}; {running} | {window}")
if size == k and running > max_total:
max_total = running
return max_total | maximum-sum-of-distinct-subarrays-with-length-k | Sliding window with updates. [100% / 50%] | BigTailWolf | 2 | 107 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,749 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2787770/Python-oror-Sliding-Window-oror-O(n)-oror-Easy-Approach-oror-Explanation | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
seen = set()
res = 0
curr = 0
for i in range(len(nums)):
if nums[i] not in seen:
if len(seen) < k:
seen.add(nums[i])
curr += nums[i]
if len(seen) == k:
res = max(res, curr)
curr -= nums[i-k+1]
seen.remove(nums[i-k+1])
else:
seen = {nums[i]}
curr = nums[i]
return res | maximum-sum-of-distinct-subarrays-with-length-k | Python || Sliding Window || O(n) || Easy Approach || Explanation | user0027Rg | 1 | 33 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,750 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783230/pythonjava-solution | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
seen = collections.defaultdict(int)
s = 0
res = 0
for i in range(k):
s += nums[i]
seen[nums[i]] += 1
if len(seen) == k:
res = s
for i in range(k, len(nums)):
s -= nums[i - k]
s += nums[i]
seen[nums[i - k]] -= 1
if seen[nums[i - k]] == 0:
del seen[nums[i - k]]
seen[nums[i]] += 1
if len(seen) == k:
res = max(res, s)
return res
class Solution {
public long maximumSubarraySum(int[] nums, int k) {
Map<Integer, Integer> seen = new HashMap<>();
long s = 0;
long res = 0;
for (int i = 0; i < k; i ++) {
s += (long)nums[i];
seen.put(nums[i], seen.getOrDefault(nums[i], 0) + 1);
}
if (seen.size() == k) {
res = s;
}
for (int i = k; i < nums.length; i ++) {
s -= nums[i - k];
s += nums[i];
seen.put(nums[i - k], seen.get(nums[i - k]) - 1);
if (seen.get(nums[i - k]) == 0) {
seen.remove(nums[i - k]);
}
seen.put(nums[i], seen.getOrDefault(nums[i], 0) + 1);
if (seen.size() == k) {
res = Math.max(res, s);
}
}
return res;
}
} | maximum-sum-of-distinct-subarrays-with-length-k | python/java solution | akaghosting | 1 | 129 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,751 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783081/Python-Simple-sliding-window-solution | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
l = 0
ctr = Counter()
curr = 0
max_sum = -math.inf
for r in range(len(nums)):
ctr[nums[r]] += 1
curr += nums[r]
while ctr[nums[r]] > 1 or (r - l + 1) > k:
curr -= nums[l]
ctr[nums[l]] -= 1
l += 1
if (r - l + 1) == k:
max_sum = max(max_sum, curr)
return max_sum if max_sum != -math.inf else 0 | maximum-sum-of-distinct-subarrays-with-length-k | [Python] Simple sliding window solution ✅ | shrined | 1 | 133 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,752 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2849716/Python-oror-HashMap%2BSliding-Window | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
n=len(nums)
ans=0
i,j=0,0
pre_sum={-1:0}
for i,val in enumerate(nums):
pre_sum[i]=pre_sum[i-1]+val
cnt={}
for i in range(n):
if nums[i] not in cnt:
cnt[nums[i]]=1
else:
cnt[nums[i]]+=1
if i>=k-1:
if len(cnt)==k:
ans=max(ans,pre_sum[i]-pre_sum[i-k])
cnt[nums[i-k+1]]-=1
if cnt[nums[i-k+1]]==0:
del cnt[nums[i-k+1]]
return ans | maximum-sum-of-distinct-subarrays-with-length-k | Python || HashMap+Sliding Window | ketan_raut | 0 | 1 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,753 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2845377/Python3-Using-Counter-and-running-window | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
# we need a set to keep track of the amount
running_set = collections.Counter(nums[:k])
# we need a sum to keep track of the running sum
running_sum = sum(nums[:k])
# we need a max sum to keep track of for the result
max_sum = running_sum if len(running_set) == k else 0
# go through the numbers
for idx, num in enumerate(nums[k:]):
# check that we really need to update
if num != nums[idx]:
# delete the previous number (if not the same)
if running_set[nums[idx]] == 1:
del running_set[nums[idx]]
else:
running_set[nums[idx]] -= 1
# adapt the sum
running_sum -= nums[idx]
# add the new number
running_set[num] += 1
# update the sum
running_sum += num
# check the lenght of the set
if len(running_set) == k:
max_sum = max(max_sum, running_sum)
return max_sum | maximum-sum-of-distinct-subarrays-with-length-k | [Python3] - Using Counter and running window | Lucew | 0 | 2 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,754 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2837751/Python-2-Pointers%3A-95-time-83-space | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
seen = set()
output, _sum = 0, 0
l = 0
for r in range(len(nums)):
num = nums[r]
while num in seen or (r - l + 1 > k):
seen.remove(nums[l])
_sum -= nums[l]
l += 1
seen.add(num)
_sum += num
length = r - l + 1
if length == k:
output = max(output, _sum)
return output | maximum-sum-of-distinct-subarrays-with-length-k | Python 2 Pointers: 95% time, 83% space | hqz3 | 0 | 4 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,755 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2821885/Python-Easy-Solution | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
if len(nums) < k:
return 0
d = defaultdict(int)
cur_sum = res = 0
for i in range(len(nums)):
cur_sum += nums[i]
d[nums[i]] += 1
if i >= k:
cur_sum -= nums[i - k]
d[nums[i - k]] -= 1
if d[nums[i - k]] <= 0:
del d[nums[i - k]]
if len(d) == k:
res = max(res, cur_sum)
return res | maximum-sum-of-distinct-subarrays-with-length-k | Python Easy Solution | kaien | 0 | 3 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,756 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2820621/EASIEST-TILL-NOW-PYTHON-SELF-EXPLANATORY-CODE | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
hp = dict()
visited = set()
sums = 0
ans = 0
for i in nums:
hp[i] = 0
i,j = 0,0
while(j < len(nums)):
sums += nums[j]
hp[nums[j]] += 1
visited.add(nums[j])
while((len(visited) > k or hp[nums[j]] > 1) and i < j):
sums -= nums[i]
hp[nums[i]] -= 1
if(hp[nums[i]] == 0):
visited.remove(nums[i])
i += 1
if(k == len(visited)):
ans = max(ans,sums)
j += 1
return ans | maximum-sum-of-distinct-subarrays-with-length-k | EASIEST TILL NOW PYTHON SELF EXPLANATORY CODE | MAYANK-M31 | 0 | 3 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,757 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2803800/Simple-oror-Easy-to-understand-oror-python | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
seen = set()
seen1 = defaultdict(int)
max_ = 0
s = 0
for i in range(0,k):
s += nums[i]
seen.add(nums[i])
seen1[nums[i]] += 1
if(len(seen) == k ):
max_ = max(max_ , s )
for i in range(k,len(nums)):
s -= nums[i-k]
s += nums[i]
seen1[nums[i-k]] -= 1
if(seen1[nums[i-k]] == 0 ):
seen.remove(nums[i-k])
seen1[nums[i]] += 1
seen.add(nums[i])
if(len(seen) == k):
max_ = max(max_ , s)
return max_ | maximum-sum-of-distinct-subarrays-with-length-k | Simple || Easy to understand || python | MB16biwas | 0 | 10 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,758 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2795229/Python-Sliding-Window-Approach-100 | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
mp = defaultdict(int)
add = 0
ans = 0
for i in range(k):
mp[nums[i]] += 1
add += nums[i]
if len(mp) == k:
ans = add
for i in range(k, len(nums)):
mp[nums[i-k]] -= 1
mp[nums[i]] += 1
add -= nums[i-k]
add += nums[i]
if mp[nums[i-k]] == 0:
del mp[nums[i-k]]
if len(mp) == k:
ans = max(ans, add)
return ans | maximum-sum-of-distinct-subarrays-with-length-k | [Python] - Sliding Window Approach 100% | leet_satyam | 0 | 13 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,759 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2793472/Python-O(n)-solution-using-python-set-and-sliding-window. | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
s = set()
sm = 0
ans = 0
i = 0
l = 0
while i < len(nums):
if len(s) != k:
if nums[i] not in s:
s.add(nums[i])
sm += nums[i]
i+=1
else:
s.remove(nums[l])
sm -= nums[l]
l += 1
else:
ans = ans if ans > sm else sm
s.remove(nums[l])
sm -= nums[l]
l+=1
if len(s) == k:
ans = ans if ans > sm else sm
return ans | maximum-sum-of-distinct-subarrays-with-length-k | Python O(n) solution using python set and sliding window. | aibekminbaev050402 | 0 | 11 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,760 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2787282/SLIDING-WINDOW%2BHASHMAP-oror-easy-to-understand. | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
hashset=set()
sums=0
maxi=0
count=0
b=0
for i in range(len(nums)):
if count<k:
if nums[i] in hashset:
j=i-count
while nums[j]!=nums[i]:
sums-=nums[j]
count-=1
hashset.remove(nums[j])
j+=1
if count==k:
maxi=max(maxi,sums)
else:
hashset.add(nums[i])
sums+=nums[i]
count+=1
if count==k:
b=1
maxi=max(maxi,sums)
elif count==k:
if nums[i] in hashset:
j=i-k
while j!=i and nums[j]!=nums[i]:
sums-=nums[j]
count-=1
hashset.remove(nums[j])
j+=1
else:
sums+=nums[i]
sums-=nums[i-k]
hashset.add(nums[i])
hashset.remove(nums[i-k])
maxi=max(maxi,sums)
return maxi | maximum-sum-of-distinct-subarrays-with-length-k | SLIDING WINDOW+HASHMAP || easy to understand. | Harsh_vardhan1812 | 0 | 8 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,761 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2786730/Python-Sliding-Window-O(n)-time | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
s,e = 0,0
cnt = defaultdict(lambda:0)
ans = 0
cur = 0
while e < len(nums):
cur += nums[e]
cnt[nums[e]] += 1
# if widow size is k
if len(cnt) == e-s+1 and k == e-s+1:
ans = max(ans, cur)
# window size reached
if e-s+1 == k:
cur -= nums[s]
# update the dictionary
if cnt[nums[s]] == 1:
cnt.pop(nums[s])
else:
cnt[nums[s]] -= 1
s+=1
e+=1
return ans | maximum-sum-of-distinct-subarrays-with-length-k | [Python] Sliding Window O(n) time | hkjit | 0 | 5 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,762 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2786451/python | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
n, start, res, sum_, d = len(nums), 0, 0, 0, defaultdict(int)
for i in range(n):
d[nums[i]]+=1
sum_+=nums[i]
while d[nums[i]]>1 or i-start+1>k:
d[nums[start]]-=1
sum_-=nums[start]
start+=1
if i-start+1==k and sum_>res:
res = sum_
return res | maximum-sum-of-distinct-subarrays-with-length-k | python | Jeremy0923 | 0 | 6 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,763 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2785413/Python-Sliding-Window-O(N) | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
hs = set()
hm = defaultdict(int)
s = 0
res = 0
l = 0
for r in range(len(nums)):
hs.add(nums[r])
hm[nums[r]] += 1
s += nums[r]
while r - l + 1 > k:
s -= nums[l]
hm[nums[l]] -= 1
if hm[nums[l]] == 0:
hs.remove(nums[l])
l += 1
if len(hs) == k:
res = max(res, s)
return res | maximum-sum-of-distinct-subarrays-with-length-k | Python Sliding Window O(N) | JSTM2022 | 0 | 12 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,764 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2785322/Python-Easy-Approach-or-Python3 | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
prefix = [nums[0]]
freq = {}
maxs = distinct = 0
for c in nums[1:]: #generating prefix sum
prefix.append(c+prefix[-1])
for i in range(len(nums)):
if i < k:
curr = prefix[i]
else:
curr = prefix[i] - prefix[i-k] #subarray sum of size k
if i >= k:
freq[nums[i - k]] -= 1
if freq.get(nums[i - k]) == 0:
distinct -= 1
freq[nums[i]] = freq.get(nums[i], 0) + 1
if freq.get(nums[i]) == 1:
distinct += 1 #Distinct will keep track of distinct elements in freq map
if distinct == k:
maxs = max(maxs , curr)
return maxs | maximum-sum-of-distinct-subarrays-with-length-k | Python Easy Approach | [ Python3 ] | alkol_21 | 0 | 26 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,765 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2784840/Using-Python | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
from collections import defaultdict
mp=defaultdict(int)
res=0
sumi=0
for i in range(k):
sumi+=nums[i]
mp[nums[i]]+=1
if(len(mp)==k):
res=max(res,sumi)
j=0
for i in range(k,len(nums)):
sumi+=nums[i]
sumi-=nums[j]
mp[nums[j]]-=1
mp[nums[i]]+=1
if(mp[nums[j]]==0):
del mp[nums[j]]
if(len(mp)==k):
res=max(res,sumi)
j+=1
return res | maximum-sum-of-distinct-subarrays-with-length-k | Using Python | ankushkumar1840 | 0 | 12 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,766 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2784191/Python-Easy-Sliding-Window-Solution | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
#sliding window
res = 0
unique = defaultdict(int)
start = sum(nums[:k])
for element in nums[:k]: unique[element] += 1
if len(unique) == k: res = start
for i in range(k, len(nums)):
delete, add = nums[i-k], nums[i]
start += (add - delete)
unique[delete] -= 1
if unique[delete] == 0: del unique[delete]
unique[add] += 1
if len(unique) == k: res = max(res, start)
return res | maximum-sum-of-distinct-subarrays-with-length-k | Python Easy Sliding Window Solution | xxHRxx | 0 | 18 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,767 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2784092/Python-Solution-with-Set | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
s = set()
c = 0
m = 0
j = 0
for i in range(len(nums)):
if nums[i] in s:
s = set()
s.add(nums[i])
j = i
m = nums[i]
else:
if nums[i] not in s:
s.add(nums[i])
m += nums[i]
if len(s) == k:
c = max(c,m)
s.remove(nums[j])
m -= nums[j]
j += 1
return max(c,sum(s)) if len(s) == k else c | maximum-sum-of-distinct-subarrays-with-length-k | Python Solution with Set | a_dityamishra | 0 | 20 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,768 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783691/Simple-Python-O(N)-with-Map-Sliding-Window | class Solution(object):
def maximumSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
#number mapped to idx... curr subarray ke mappings honge to check repeititions
maps = {}
ans = 0
l, r = 0, 0
curr = 0
while r < len(nums):
while l < r and (len(maps) >= k or nums[r] in maps):
curr -= nums[l]
maps.pop(nums[l])
l += 1
curr += nums[r]
maps[nums[r]] = r
if len(maps) == k:
ans = max(curr, ans)
r += 1
return ans | maximum-sum-of-distinct-subarrays-with-length-k | ✔️ Simple Python O(N) with Map, Sliding Window | jaygala223 | 0 | 33 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,769 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783619/Python3-or-Sliding-Window-or-Simple | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
runningSum = 0
seen = {}
i, j = 0, 0
maxSoFar = float('-inf')
count = 0
while i < len(nums):
count += 1
while (nums[i] in seen and seen[nums[i]] == True) or count > k:
seen[nums[j]] = False
runningSum -= nums[j]
count -= 1
j += 1
seen[nums[i]] = True
runningSum += nums[i]
if count == k:
maxSoFar = max(maxSoFar, runningSum)
i += 1
return maxSoFar if maxSoFar != float('-inf') else 0 | maximum-sum-of-distinct-subarrays-with-length-k | Python3 | Sliding Window | Simple | vikinam97 | 0 | 10 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,770 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783585/Python-Intuitive-Sliding-Window. | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
n = len(nums)
res = 0
sumK = 0
window = {}
for i, val in enumerate(nums):
sumK += val
window[val] = window.get(val, 0) + 1
if i >= k - 1:
if len(window) == k:
res = max(res, sumK)
remove = nums[i - k + 1]
sumK -= remove
window[remove] -= 1
if window[remove] == 0:
window.pop(remove)
return res | maximum-sum-of-distinct-subarrays-with-length-k | Python Intuitive Sliding Window. | MaverickEyedea | 0 | 11 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,771 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783505/Python-Set-%2B-Queue-%2B-Total-Count | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
#the current set
s = set()
#the result
su = 0
#a queue of the current set
q = Deque()
#the total count of the values in the set
sa = 0
for i, n in enumerate(nums):
if n in s:
while q and q[0] != n:
v = q.popleft()
s.remove(v)
sa -= v
if q[0] == n:
v =q.popleft()
s.remove(v)
sa -= v
sa += n
s.add(n)
q.append(n)
if len(q) > k:
v =q.popleft()
s.remove(v)
sa -= v
if len(s) == k:
su = max(su , sa)
return su | maximum-sum-of-distinct-subarrays-with-length-k | [Python🤫🐍🐍🐍] Set + Queue + Total Count | xmky | 0 | 12 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,772 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783446/Easy-Understand-understandable | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
res=collections.Counter()
N=len(nums)
best=0
curr=0
for r in range(N):
res[nums[r]]+=1
curr+=nums[r]
if r-k>=0:
res[nums[r-k]]-=1
if res[nums[r-k]]==0:
del res[nums[r-k]]
curr-=nums[r-k]
if r-k+1>=0:
if len(res)==k:
best=max(best,curr)
return best | maximum-sum-of-distinct-subarrays-with-length-k | Easy Understand understandable | Motaharozzaman1996 | 0 | 34 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,773 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783279/Python | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
ans=0
curr=0
hm={}
for i in range(len(nums)):
curr+=nums[i]
if nums[i] in hm:
hm[nums[i]]+=1
else:
hm[nums[i]]=1
if i>=k:
hm[nums[i-k]]-=1
curr-=nums[i-k]
if nums[i-k] in hm:
if hm[nums[i-k]]==0:
hm.pop(nums[i-k])
if len(hm)==k:
ans=max(ans,curr)
return ans | maximum-sum-of-distinct-subarrays-with-length-k | Python | srikanthreddy691 | 0 | 24 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,774 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783270/Python3-Sliding-Window-and-Dictionary | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
nums.append(nums[-1])
i,j=0,len(nums)
a=sum(nums[i:i+k])
s=Counter(nums[i:i+k])
p=sum(1<v for v in s.values())
m=0
while i+k<j:
if p==0:
m=max(m,a)
a+=nums[i+k]-nums[i]
s[nums[i]]-=1
if s[nums[i]]==1:
p-=1
s[nums[i+k]]+=1
if s[nums[i+k]]==2:
p+=1
i+=1
return m | maximum-sum-of-distinct-subarrays-with-length-k | Python3, Sliding Window and Dictionary | Silvia42 | 0 | 27 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,775 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783264/Python3-or-Sliding-Window-%2B-Set-or-Explained | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
dq = deque()
vis = set()
n = len(nums)
currSum = 0
ans = 0
for i in range(n):
dq.append(nums[i])
currSum+=nums[i]
while dq and len(dq)>k:
ele = dq.popleft()
currSum-=ele
vis.remove(ele)
if nums[i] in vis:
while dq and dq[0]!=nums[i]:
ele = dq.popleft()
currSum-=ele
vis.remove(ele)
if dq:
ele = dq.popleft()
currSum-=ele
vis.remove(ele)
vis.add(nums[i])
if len(dq) == k:
ans = max(ans,currSum)
return ans | maximum-sum-of-distinct-subarrays-with-length-k | [Python3] | Sliding Window + Set | Explained | swapnilsingh421 | 0 | 48 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,776 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783206/python3-simple-prefix-sum-solution | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
## RC ##
## APPROACH : SUBARRAY SUM ##
if k == 1:
return max([0] + nums)
rsum={-1:0}
idx={}
res = 0
start=-1
for i in range(len(nums)):
rsum[i] = rsum[i-1] + nums[i]
if nums[i] in idx:
start = max(start, idx[nums[i]])
start = max(start, i-k)
if i - start == k:
res = max(res, rsum[i] - rsum[start])
idx[nums[i]] = i
return res | maximum-sum-of-distinct-subarrays-with-length-k | [python3] simple prefix sum solution | 101leetcode | 0 | 35 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,777 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783122/Pytho3n-sliding-window | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
ans = ii = rsm = 0
seen = set()
for i, x in enumerate(nums):
while x in seen or i-ii == k:
seen.remove(nums[ii])
rsm -= nums[ii]
ii += 1
seen.add(x)
rsm += x
if i-ii == k-1: ans = max(ans, rsm)
return ans | maximum-sum-of-distinct-subarrays-with-length-k | [Pytho3n] sliding window | ye15 | 0 | 70 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,778 |
https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783102/Python-Sliding-Window-Solution | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
left, right = 0,0
max_sum = 0
n = len(nums)
seen = {}
current_sum = 0
while right<n:
seen[nums[right]] = seen.get(nums[right], 0)+1
current_sum += nums[right]
if right-left+1 == k:
if len(seen) == k:
max_sum = max(max_sum, current_sum)
if seen[nums[left]]>1:
seen[nums[left]]-=1
else:
del seen[nums[left]]
current_sum-=nums[left]
left+=1
right+=1
return max_sum | maximum-sum-of-distinct-subarrays-with-length-k | Python Sliding Window Solution | dhanu084 | 0 | 60 | maximum sum of distinct subarrays with length k | 2,461 | 0.344 | Medium | 33,779 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783147/Python3-priority-queues | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
q = costs[:candidates]
qq = costs[max(candidates, len(costs)-candidates):]
heapify(q)
heapify(qq)
ans = 0
i, ii = candidates, len(costs)-candidates-1
for _ in range(k):
if not qq or q and q[0] <= qq[0]:
ans += heappop(q)
if i <= ii:
heappush(q, costs[i])
i += 1
else:
ans += heappop(qq)
if i <= ii:
heappush(qq, costs[ii])
ii -= 1
return ans | total-cost-to-hire-k-workers | [Python3] priority queues | ye15 | 24 | 1,200 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,780 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783503/Python-easy-to-understand-heap-solution | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
from heapq import heappush, heappop
heap = []
p1 = 0
p2 = len(costs)-1
while(p1 < candidates):
heappush(heap, (costs[p1], p1))
p1 += 1
while(p2 >= len(costs)-candidates and p2 >= p1):
heappush(heap, (costs[p2], p2))
p2 -= 1
res = 0
for i in range(k):
c, idx = heappop(heap)
res += c
if idx < p1:
if p1 <= p2:
heappush(heap, (costs[p1], p1))
p1 += 1
else:
if p1 <= p2:
heappush(heap, (costs[p2], p2))
p2 -= 1
return res | total-cost-to-hire-k-workers | Python easy to understand heap solution | ankurkumarpankaj | 3 | 111 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,781 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783375/Python3-Heap | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
total = 0
i, j = candidates, len(costs)-candidates-1
if len(costs) <= 2 * candidates:
heap = [(x,0) for x in costs]
else:
heap = [(x,0) for x in costs[:candidates]] + [(x,1) for x in costs[len(costs)-candidates:]]
heapq.heapify(heap)
for _ in range(k):
cost, direction = heapq.heappop(heap)
total += cost
if i <= j:
if direction:
heapq.heappush(heap, (costs[j], 1))
j -= 1
else:
heapq.heappush(heap, (costs[i], 0))
i += 1
return total | total-cost-to-hire-k-workers | [Python3] Heap | user1793l | 2 | 35 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,782 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783063/Python-Heap-solution | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
output = 0
heap = []
l, r = 0, len(costs) - 1
j = candidates
while l <= r and j:
heapq.heappush(heap, (costs[l], l))
# If l and r point to the same cell in costs don't push it twice
if l != r:
heapq.heappush(heap, (costs[r], r))
l += 1
r -= 1
j -= 1
while k:
val, idx = heapq.heappop(heap)
output += val
if l <= r:
# After every hire a new spot in the hiring pool opens we need to fill
# We must figure out if the last candidate that was popped was from the left side
# or the right side
if abs(idx - l) <= abs(idx - r):
heapq.heappush(heap, (costs[l], l))
l += 1
else:
heapq.heappush(heap, (costs[r], r))
r -= 1
k -= 1
return output | total-cost-to-hire-k-workers | [Python] Heap solution ✅ | shrined | 2 | 77 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,783 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2849677/Python-oror-Heap | class Solution:
def totalCost(self, costs: List[int], k: int, can: int) -> int:
l_heap,r_heap=[],[]
ans=0
n=len(costs)
if n<=2*can:
costs.sort()
return sum(costs[:k])
l_heap=costs[:can]
r_heap=costs[n-can:]
heapify(l_heap)
heapify(r_heap)
i,j=can,n-can-1
while k:
if not l_heap:
ans+= heappop(r_heap)
if i<=j:
heappush(r_heap,costs[j])
j-=1
elif not r_heap or l_heap[0]<=r_heap[0]:
ans+= heappop(l_heap)
if i<=j:
heappush(l_heap,costs[i])
i+=1
else:
ans+= heappop(r_heap)
if i<=j:
heappush(r_heap,costs[j])
j-=1
k-=1
return ans | total-cost-to-hire-k-workers | Python || Heap | ketan_raut | 0 | 1 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,784 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2845380/Python3-One-Min-Heap | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
# we can use two pointers and a min heap using the cost and index
candidates_heap = [(cost, idx, True) for idx, cost in enumerate(costs[:candidates])]
# get the secon start index
start_index = max(candidates, len(costs)-candidates) # candidates can already overlap
candidates_heap += [(cost, idx, False) for idx, cost in enumerate(costs[start_index:], start_index)]
# heapify the thing
heapq.heapify(candidates_heap)
print(candidates_heap)
# make two pointers
left = candidates - 1
right = len(costs)-candidates
# go through the process
result = 0
for _ in range(k):
# pop the worker
worker_cost, idx, is_left = heapq.heappop(candidates_heap)
print(worker_cost, is_left)
result += worker_cost
# update the heap
if left < right - 1:
# check wich pointer to update
if is_left:
left += 1
heapq.heappush(candidates_heap, (costs[left], left, True))
else:
right -= 1
heapq.heappush(candidates_heap, (costs[right], right, False))
return result | total-cost-to-hire-k-workers | [Python3] - One Min-Heap | Lucew | 0 | 1 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,785 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2800617/Python-easy-solution | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
n = len(costs)
arr = []
heapq.heapify(arr)
ans = 0
if 2*candidates <= n:
for i in range(candidates):
heapq.heappush(arr, (costs[i], i))
heapq.heappush(arr, (costs[n-i-1], n-i-1))
left, right = candidates, n-candidates-1
while k:
k -= 1
c, idx = heapq.heappop(arr)
ans += c
if idx < left and left <= right:
heapq.heappush(arr, (costs[left], left))
left += 1
elif idx > right and left <= right:
heapq.heappush(arr, (costs[right], right))
right -= 1
return ans
for idx, ele in enumerate(costs):
heapq.heappush(arr, (ele, idx))
while k:
k -= 1
c, idx = heapq.heappop(arr)
ans += c
return ans | total-cost-to-hire-k-workers | Python easy solution | subidit | 0 | 9 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,786 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2789548/Two-queues-60-speed | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
if len(costs) <= 2 * candidates:
return sum(nsmallest(k, costs))
left = costs[:candidates]
right = costs[-candidates:]
heapify(left)
heapify(right)
i, j = candidates, len(costs) - candidates - 1
ans = 0
while i <= j:
if left[0] <= right[0]:
ans += heappop(left)
heappush(left, costs[i])
i += 1
else:
ans += heappop(right)
heappush(right, costs[j])
j -= 1
k -= 1
if k == 0:
return ans
left.extend(right)
return ans + sum(nsmallest(k, left)) | total-cost-to-hire-k-workers | Two queues, 60% speed | EvgenySH | 0 | 7 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,787 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2786802/Python-Heap-solution | class Solution:
def totalCost(self, costs: List[int], k: int, c: int) -> int:
l = 0
r = len(costs)-1
lHeap = []
rHeap = []
ans = []
seen = set()
while l < c:
heapq.heappush(lHeap, (costs[l], l))
heapq.heappush(rHeap, (costs[r], r))
r-=1
l+=1
while k > 0:
leftElem = lHeap[0]
rightElem = rHeap[0]
if leftElem[0] <= rightElem[0]:
if leftElem[1] not in seen:
ans.append(leftElem[0])
seen.add(leftElem[1])
k-=1
heapq.heappop(lHeap)
if l < len(costs):
heapq.heappush(lHeap, (costs[l], l))
l+=1
elif rightElem[0] < leftElem[0]:
if rightElem[1] not in seen:
ans.append(rightElem[0])
seen.add(rightElem[1])
k-=1
heapq.heappop(rHeap)
if r > 0:
heapq.heappush(rHeap, (costs[r], r))
r-=1
return sum(ans) | total-cost-to-hire-k-workers | [Python] Heap solution | hkjit | 0 | 6 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,788 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2785417/Python-heap | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
res = 0
if candidates * 2 >= len(costs):
hp = costs
heapify(hp)
for i in range(k):
res += heappop(hp)
return res
hpl, hpr = costs[:candidates], costs[len(costs) - candidates:]
heapq.heapify(hpl)
heapq.heapify(hpr)
l, r = candidates, len(costs) - candidates - 1
for i in range(k):
if l > r:
hp = hpl + hpr
heapq.heapify(hp)
temp = i
while temp < k:
res += heappop(hp)
# print(res)
temp += 1
return res
if hpl[0] <= hpr[0]:
res += heappop(hpl)
# print(res)
heappush(hpl, costs[l])
l += 1
else:
res += heappop(hpr)
# print(res)
heappush(hpr, costs[r])
r -= 1
return res | total-cost-to-hire-k-workers | Python heap | JSTM2022 | 0 | 20 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,789 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2785063/python3-heapq-and-two-pointer-sol-for-reference. | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
C = len(costs)
c = []
start = candidates-1
end = max(C-candidates, start+1)
ans = 0
for i in range(candidates):
heapq.heappush(c, (costs[i],i))
for j in range(C-1,end-1,-1):
heapq.heappush(c, (costs[j], j))
while c and k and start < end:
v,idx = heapq.heappop(c)
ans += v
if idx <= start and start+1 < end:
start += 1
heapq.heappush(c, (costs[start], start))
elif idx >= end and end-1 > start:
end -= 1
heapq.heappush(c,(costs[end], end))
k -= 1
while c and k:
v,idx = heapq.heappop(c)
ans += v
k -= 1
return ans | total-cost-to-hire-k-workers | [python3] heapq and two pointer sol for reference. | vadhri_venkat | 0 | 9 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,790 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2784332/Simple-Two-heap-solution | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
if 2*candidates >= len(costs):
return sum(sorted(costs)[:k])
else:
heapl = costs[:candidates]
heapify(heapl)
min1, max1 = 0, candidates-1
heapr = costs[-candidates:]
heapify(heapr)
min2, max2 = len(costs) - candidates, len(costs) - 1
remaining = k
total = 0
for c in range(k):
if heapl[0] <= heapr[0]:
total += heappop(heapl)
max1 += 1
heappush(heapl, costs[max1])
else:
total += heappop(heapr)
min2 -= 1
heappush(heapr, costs[min2])
remaining -= 1
if max1 >= min2 - 1:
# can merge both heaps now
total += sum(sorted(heapl + heapr)[:remaining])
break
return total | total-cost-to-hire-k-workers | ✅ Simple - Two heap solution | lcshiung | 0 | 7 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,791 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2784228/Python3-Simple-Two-Minheap-Solution | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
if candidates * 2 >= len(costs):
costs.sort()
return sum(costs[:k])
else:
pointer1 = candidates-1
pointer2 = len(costs) - candidates
arr1, arr2 = costs[:candidates], costs[-candidates:]
heapify(arr1)
heapify(arr2)
res = 0
for element in range(k):
if arr1 and arr2:
if arr1[0] <= arr2[0]:
res += heappop(arr1)
pointer1 += 1
if pointer1 < pointer2:
heappush(arr1, costs[pointer1])
else:
res += heappop(arr2)
pointer2 -= 1
if pointer1 < pointer2:
heappush(arr2, costs[pointer2])
else:
if arr1:
res += heappop(arr1)
else:
res += heappop(arr2)
return res | total-cost-to-hire-k-workers | Python3 Simple Two Minheap Solution | xxHRxx | 0 | 13 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,792 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2784180/Python-2-heaps-and-deque-solution | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
s = 0
n = len(costs)
heap1 , heap2 = [],[]
visited = set()
for i in range(candidates):
heappush(heap1, costs[i])
visited.add(i)
for i in range(n-candidates, n):
if i in visited:
continue
heappush(heap2, costs[i])
visited.add(i)
remaining = deque()
for i in range(n):
if i not in visited:
remaining.append(costs[i])
for i in range(k):
c1 = heap1[0] if heap1 else inf
c2 = heap2[0] if heap2 else inf
if c1 <= c2:
s+=heappop(heap1) if heap1 else 0
if remaining:
heappush(heap1, remaining.popleft())
else:
s+=heappop(heap2) if heap2 else 0
if remaining:
heappush(heap2, remaining.pop())
return s | total-cost-to-hire-k-workers | Python 2 heaps and deque solution | dhanu084 | 0 | 20 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,793 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783641/Python3-or-2-Heap-or-Simple | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
left, right= [], []
li = 0
ri = len(costs)-1
sumCost = 0
seen = {}
for _ in range(k):
# fiiling left the candidates for session
while len(left) < candidates and li < len(costs):
if li in seen:
li += 1
continue
heapq.heappush(left, (costs[li], li))
li += 1
# fiiling right the candidates for session
while len(right) < candidates and ri >= 0:
if ri in seen:
ri -= 1
continue
heapq.heappush(right, (costs[ri], ri))
ri -= 1
# removing the invalid candidates already chosen
while left[0][1] in seen:
heapq.heappop(left)
while right[0][1] in seen:
heapq.heappop(right)
# selecting the minimimal cost candidate
t = 0
if left[0] < right[0]:
t = heapq.heappop(left)
else:
t = heapq.heappop(right)
seen[t[1]] = True
sumCost += t[0]
return sumCost | total-cost-to-hire-k-workers | Python3 | 2 Heap | Simple | vikinam97 | 0 | 10 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,794 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783520/Python-Answer-Two-Heaps | class Solution:
def totalCost(self, costs: List[int], k: int, c: int) -> int:
N = len(costs)
cos = [[v,i] for i,v in enumerate(costs)]
h1 = cos[0:c]
heapify(h1)
#only fill up the second heap when the C is half the the total candidates
if len(costs) >= c *2:
h2 = cos[N-c:]
else:
h2 = cos[len(h1):]
heapify(h2)
#leftovers
rest = cos[c:N-c]
res = 0
#pointers to the left and right values of leftovers
l = 0
r = len(rest) - 1
while k > 0:
if (h1 and h2 and h1[0][0] <= h2[0][0]) or (not h2 and h1):
res += h1[0][0]
heappop(h1)
if l <= r:
heappush(h1, rest[l])
l+=1
elif (h1 and h2) or (not h1 and h2) :
res += h2[0][0]
heappop(h2)
if l <= r:
heappush(h2, rest[r])
r-=1
else:
print("NO MORE ANYTHING")
k-= 1
return res | total-cost-to-hire-k-workers | [Python Answer🤫🐍🐍🐍] Two Heaps | xmky | 0 | 15 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,795 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783429/Python-3-or-Maintain-2-heaps | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
ans=0
arr1=costs[:candidates]
arr2=costs[max(candidates, len(costs)-candidates):]
i, ii = candidates, len(costs)-candidates-1
heapify(arr1)
heapify(arr2)
count=0
while count!=k:
if arr1 and (not arr2 or arr1[0] <= arr2[0]):
ans+=heappop(arr1)
if i <= ii:
heappush(arr1, costs[i])
i += 1
else:
ans+=heappop(arr2)
if i <= ii:
heappush(arr2, costs[ii])
ii -= 1
count+=1
return ans | total-cost-to-hire-k-workers | Python 3 | Maintain 2 heaps | RickSanchez101 | 0 | 8 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,796 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783373/Python3-or-Two-Min-heap-%2B-deque-or-Explanation | class Solution:
def totalCost(self, costs: List[int], k: int, c: int) -> int:
leftpq = []
rightpq = []
ans = 0
n = len(costs)
for i in range(c):
heappush(leftpq,[costs[i],i])
for j in range(n-1,max(n-1-c,c-1),-1):
heappush(rightpq,[costs[j],j])
rem = deque([[costs[i],i] for i in range(c,n-c)])
while k>0:
if leftpq and rightpq:
leftval,leftind = heappop(leftpq)
rightval,rightind = heappop(rightpq)
if leftval < rightval:
heappush(rightpq,[rightval,rightind])
ans+=leftval
if len(rem) > 0:
heappush(leftpq,rem.popleft())
elif leftval > rightval:
heappush(leftpq,[leftval,leftind])
ans+=rightval
if len(rem) > 0:
heappush(rightpq,rem.pop())
else:
if leftind < rightind:
heappush(rightpq,[rightval,rightind])
ans+=leftval
if len(rem) > 0:
heappush(leftpq,rem.popleft())
else:
heappush(leftpq,[leftval,leftind])
ans+=rightval
if len(rem) > 0:
heappush(rightpq,rem.pop())
elif leftpq:
leftval,leftind = heappop(leftpq)
ans+=leftval
if len(rem) > 0:
heappush(leftpq,rem.popleft())
elif rightpq:
rightval,rightind = heappop(rightpq)
ans+=rightval
if len(rem) > 0:
heappush(rightpq,rem.pop())
k-=1
return ans | total-cost-to-hire-k-workers | [Python3] | Two Min-heap + deque | Explanation | swapnilsingh421 | 0 | 14 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,797 |
https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783235/pythonjava-2-heaps | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
n = len(costs)
first = []
last = []
res = 0
l = 0
r = len(costs) - 1
for i in range(candidates):
heapq.heappush(first, costs[l])
heapq.heappush(last, costs[r])
l += 1
r -= 1
if l + 1 > r:
break
for i in range(k):
if not last or (first and first[0] <= last[0]):
res += heapq.heappop(first)
if l <= r:
heapq.heappush(first, costs[l])
l += 1
elif not first or (last and last[0] < first[0]):
res += heapq.heappop(last)
if r >= l:
heapq.heappush(last, costs[r])
r -= 1
return res
class Solution {
public long totalCost(int[] costs, int k, int candidates) {
int n = costs.length;
Queue<Integer> first = new PriorityQueue<>();
Queue<Integer> last = new PriorityQueue<>();
long res = 0;
int l = 0;
int r = n - 1;
for (int i = 0; i < candidates; i ++) {
first.offer(costs[l]);
last.offer(costs[r]);
l ++;
r --;
if (l + 1 > r) {
break;
}
}
for (int i = 0; i < k; i ++) {
if (last.isEmpty() || (!first.isEmpty() && first.peek() <= last.peek())) {
res += (long)first.poll();
if (l <= r) {
first.offer(costs[l]);
l ++;
}
} else if (first.isEmpty() || (!last.isEmpty() && last.peek() < first.peek())) {
res += (long)last.poll();
if (r >= l) {
last.offer(costs[r]);
r --;
}
}
}
return res;
}
} | total-cost-to-hire-k-workers | python/java 2 heaps | akaghosting | 0 | 10 | total cost to hire k workers | 2,462 | 0.374 | Medium | 33,798 |
https://leetcode.com/problems/minimum-total-distance-traveled/discuss/2783245/Python3-O(MN)-DP | class Solution:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
robot.sort()
factory.sort()
m, n = len(robot), len(factory)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(m): dp[i][-1] = inf
for j in range(n-1, -1, -1):
prefix = 0
qq = deque([(m, 0)])
for i in range(m-1, -1, -1):
prefix += abs(robot[i] - factory[j][0])
if qq[0][0] > i+factory[j][1]: qq.popleft()
while qq and qq[-1][1] >= dp[i][j+1] - prefix: qq.pop()
qq.append((i, dp[i][j+1] - prefix))
dp[i][j] = qq[0][1] + prefix
return dp[0][0] | minimum-total-distance-traveled | [Python3] O(MN) DP | ye15 | 13 | 769 | minimum total distance traveled | 2,463 | 0.397 | Hard | 33,799 |
Subsets and Splits