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-score-from-performing-multiplication-operations/discuss/1075495/Python3-bottom-up-dp | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
n, m = len(nums), len(multipliers)
dp = [[0]*m for _ in range(m+1)]
for i in reversed(range(m)):
for j in range(i, m):
k = i + m - j - 1
dp[i][j] = max(nums[i] * multipliers[k] + dp[i+1][j], nums[j-m+n] * multipliers[k] + dp[i][j-1])
return dp[0][-1] | maximum-score-from-performing-multiplication-operations | [Python3] bottom-up dp | ye15 | 64 | 5,800 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,400 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1075495/Python3-bottom-up-dp | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
@lru_cache(2000)
def fn(lo, hi, k):
"""Return max score from nums[lo:hi+1]."""
if k == len(multipliers): return 0
return max(nums[lo] * multipliers[k] + fn(lo+1, hi, k+1), nums[hi] * multipliers[k] + fn(lo, hi-1, k+1))
return fn(0, len(nums)-1, 0) | maximum-score-from-performing-multiplication-operations | [Python3] bottom-up dp | ye15 | 64 | 5,800 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,401 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1898863/Python-or-DP-or-With-Explanation | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
# dp[i, left]: the maximum possible score if we have already done 'i' total operations
# and used 'left' numbers from the left side.
# if we know the used 'left' numbers from the leftmost side,
# then the index of the rightmost element = n-1-(i-left)
n = len(nums)
m = len(multipliers)
dp = [[0] * (m + 1) for _ in range(m + 1)]
# why we move backwards (how to determine the order)?
# 1. outer loop: we must move backwards because only in this way we can make full use of all the information we have met.
# 2. inner loop: left must less of equal to i, so the inner loop move backwards.
for i in range(m-1, -1, -1):
for left in range(i, -1, -1):
mult = multipliers[i]
right = n - 1 - (i - left)
# If we choose left, the the next operation will occur at (i + 1, left + 1)
left_choice = mult * nums[left] + dp[i + 1][left + 1]
# If we choose right, the the next operation will occur at (i + 1, left)
right_choice = mult * nums[right] + dp[i + 1][left]
dp[i][left] = max(left_choice, right_choice)
return dp[0][0] | maximum-score-from-performing-multiplication-operations | Python | DP | With Explanation | Mikey98 | 6 | 620 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,402 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2581806/SIMPLE-PYTHON3-SOLUTION-98-less-memory-and-faster | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
dp = [0] * (len(multipliers) + 1)
for m in range(len(multipliers) - 1, -1, -1):
pd = [0] * (m + 1)
for l in range(m, -1, -1):
pd[l] = max(dp[l + 1] + multipliers[m] * nums[l],
dp[l] + multipliers[m] * nums[~(m - l)])
dp = pd
return dp[0] | maximum-score-from-performing-multiplication-operations | β
β SIMPLE PYTHON3 SOLUTION β
β98% less memory and faster | rajukommula | 2 | 313 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,403 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2625975/Python-Dp(Memoization)-Solution-oror-Faster-than-99.70-Python-Users | class Solution:
def maximumScore(self, nums: List[int], multi: List[int]) -> int:
memo = {}
def solve(b,e,i):
if i >= len(multi):
return 0
if (b,i) in memo:
return memo[(b,i)]
x= max(solve(b+1,e,i+1)+nums[b]*multi[i],solve(b,e-1,i+1)+nums[e]*multi[i])
memo[(b,i)] = x
return x
return solve(0,len(nums)-1,0) | maximum-score-from-performing-multiplication-operations | Python Dp(Memoization) Solution || Faster than 99.70% Python Users | hoo__mann | 1 | 13 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,404 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2582278/Python-Accepted | class Solution:
def maximumScore(self, nums: List[int], mul: List[int]) -> int:
dp = [0] * (len(mul) + 1)
for m in range(len(mul) - 1, -1, -1):
pd = [0] * (m + 1)
for l in range(m, -1, -1):
pd[l] = max(dp[l + 1] + mul[m] * nums[l],
dp[l] + mul[m] * nums[~(m - l)])
dp = pd
return dp[0] | maximum-score-from-performing-multiplication-operations | Python Accepted β
| Khacker | 1 | 106 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,405 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2581827/Python3-Fighting-The-Ugly-Battle-of-TLE-and-MLE | class Solution1:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
"""MLE
"""
M, N = len(multipliers), len(nums)
@lru_cache(maxsize=None)
def dfs(lo: int, idx: int) -> int:
if idx == M:
return 0
hi = N - (idx - lo) - 1
return max(
multipliers[idx] * nums[lo] + dfs(lo + 1, idx + 1),
multipliers[idx] * nums[hi] + dfs(lo, idx + 1),
)
return dfs(0, 0) | maximum-score-from-performing-multiplication-operations | [Python3] Fighting The Ugly Battle of TLE and MLE | FanchenBao | 1 | 56 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,406 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2581827/Python3-Fighting-The-Ugly-Battle-of-TLE-and-MLE | class Solution2:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
"""Worse than solution 1, TLE
"""
M, N = len(multipliers), len(nums)
dp = [[-math.inf] * M for _ in range(M)]
def dfs(lo: int, idx: int) -> int:
if idx == M:
return 0
if dp[lo][idx] == -math.inf:
c1 = multipliers[idx] * nums[lo] + dfs(lo + 1, idx + 1)
c2 = multipliers[idx] * nums[N - (idx - lo) - 1] + dfs(lo, idx + 1)
dp[lo][idx] = max(c1, c2)
return dp[lo][idx]
return dfs(0, 0) | maximum-score-from-performing-multiplication-operations | [Python3] Fighting The Ugly Battle of TLE and MLE | FanchenBao | 1 | 56 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,407 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2581827/Python3-Fighting-The-Ugly-Battle-of-TLE-and-MLE | class Solution3:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
"""Bottom up 2D DP, TLE
"""
M, N = len(multipliers), len(nums)
dp = [[-math.inf] * M for _ in range(M)]
for idx in range(M - 1, -1, -1):
for lo in range(idx + 1):
hi = N - (idx - lo) - 1
c1 = multipliers[idx] * nums[lo] + (0 if lo + 1 == M or idx + 1 == M else dp[lo + 1][idx + 1])
c2 = multipliers[idx] * nums[hi] + (0 if idx + 1 == M else dp[lo][idx + 1])
dp[lo][idx] = max(c1, c2)
return dp[0][0] | maximum-score-from-performing-multiplication-operations | [Python3] Fighting The Ugly Battle of TLE and MLE | FanchenBao | 1 | 56 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,408 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2581827/Python3-Fighting-The-Ugly-Battle-of-TLE-and-MLE | class Solution4:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
"""Bottom up 2D DP, without if/else but with additional column and row
Exactly the same as official approach 3, TLE
"""
M, N = len(multipliers), len(nums)
dp = [[0] * (M + 1) for _ in range(M + 1)]
for idx in range(M - 1, -1, -1):
for lo in range(idx + 1):
hi = N - (idx - lo) - 1
c1 = multipliers[idx] * nums[lo] + dp[lo + 1][idx + 1]
c2 = multipliers[idx] * nums[hi] + dp[lo][idx + 1]
dp[lo][idx] = max(c1, c2)
return dp[0][0] | maximum-score-from-performing-multiplication-operations | [Python3] Fighting The Ugly Battle of TLE and MLE | FanchenBao | 1 | 56 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,409 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2581827/Python3-Fighting-The-Ugly-Battle-of-TLE-and-MLE | class Solution5:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
"""Bottom up 1D DP, TLE
"""
M, N = len(multipliers), len(nums)
dp = [-math.inf] * M
for idx in range(M - 1, -1, -1):
for lo in range(idx + 1):
hi = N - (idx - lo) - 1
c1 = multipliers[idx] * nums[lo] + (0 if lo + 1 == M or idx + 1 == M else dp[lo + 1])
c2 = multipliers[idx] * nums[hi] + (0 if idx + 1 == M else dp[lo])
dp[lo] = max(c1, c2)
return dp[0] | maximum-score-from-performing-multiplication-operations | [Python3] Fighting The Ugly Battle of TLE and MLE | FanchenBao | 1 | 56 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,410 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2581827/Python3-Fighting-The-Ugly-Battle-of-TLE-and-MLE | class Solution6:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
"""Follow https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1075448/Python-DP-Clear-the-Cache!
Clear cache between tests to avoid MLE.
Does avoid MLE, but nope, got TLE instead.
"""
M, N = len(multipliers), len(nums)
@lru_cache(maxsize=None)
def dfs(lo: int, idx: int) -> int:
if idx == M:
return 0
hi = N - (idx - lo) - 1
return max(
multipliers[idx] * nums[lo] + dfs(lo + 1, idx + 1),
multipliers[idx] * nums[hi] + dfs(lo, idx + 1),
)
res = dfs(0, 0)
dfs.cache_clear()
return res | maximum-score-from-performing-multiplication-operations | [Python3] Fighting The Ugly Battle of TLE and MLE | FanchenBao | 1 | 56 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,411 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2581827/Python3-Fighting-The-Ugly-Battle-of-TLE-and-MLE | class Solution7:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
"""LeetCode 1770
Bottom up 1D DP, without if/else
What a journey!
* lru_cache memory limit exceeded (MLE)
* 2D DP top down time limit exceeded (TLE)
* 2D DP bottom up with if/else, TLE
* 2D DP bottom up without if/else, but with additional column and row, TLE
* 1D DP bottom up with if/else, TLE
* lru_cache with cache clearing, TLE
* 1D DP bottom up without if/else passed, with very good time.
Can you believe it? How slow is Python's if/else? Apparently it is very
slow.
The problem itself is pretty standard DP. The first breakthrough is to
realize that for nums, we only need to keep lo. hi can be computed from
lo and idx.
The second breakthrough is just being patient and convert the naive DP
to the most optimal version, which is 1D DP without if/else.
O(M^2), 3659 ms, faster than 99.82%
"""
M, N = len(multipliers), len(nums)
dp = [max(multipliers[M - 1] * nums[lo], multipliers[M - 1] * nums[N - M + lo]) for lo in range(M)]
for idx in range(M - 2, -1, -1):
for lo in range(idx + 1):
hi = N - (idx - lo) - 1
c1 = multipliers[idx] * nums[lo] + dp[lo + 1]
c2 = multipliers[idx] * nums[hi] + dp[lo]
dp[lo] = max(c1, c2)
return dp[0] | maximum-score-from-performing-multiplication-operations | [Python3] Fighting The Ugly Battle of TLE and MLE | FanchenBao | 1 | 56 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,412 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2581786/python-3-or-optimal-dp-or-O(m2)O(m) | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
n, m = len(nums), len(multipliers)
prev = [0] * (m + 1)
for i in range(m - 1, -1, -1):
cur = [0] * (i + 2)
for left in range(i, -1, -1):
right = n + left - i - 1
cur[left] = max(nums[left] * multipliers[i] + prev[left + 1],
nums[right] * multipliers[i] + prev[left])
prev = cur
return prev[0] | maximum-score-from-performing-multiplication-operations | python 3 | optimal dp | O(m^2)/O(m) | dereky4 | 1 | 116 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,413 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1769349/Python3-Always-getting-time-limit-exceeded | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
n, m = len(nums), len(multipliers)
dp = [[0] * (m + 1) for _ in range(m + 1)]
for left in range(1, m + 1):
dp[left][0] = dp[left - 1][0] + multipliers[left - 1] * nums[left - 1]
for right in range(1, m + 1):
dp[0][right] = dp[0][right - 1] + multipliers[right - 1] * nums[len(nums) - right]
max_points = max(dp[-1][0], dp[0][-1])
for left in range(1, m + 1):
for right in range(1, m + 1):
i = left + right
if i > len(multipliers):
continue
mult = multipliers[i - 1]
dp[left][right] = max(mult * nums[left - 1] + dp[left - 1][right],
mult * nums[len(nums) - right] + dp[left][right - 1])
if i == len(multipliers):
max_points = max(max_points, dp[left][right])
return max_points | maximum-score-from-performing-multiplication-operations | Python3 - Always getting time limit exceeded | benjie | 1 | 203 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,414 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1674863/Well-coded-oror-Simple-and-Concise-oror-Memoization | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
s,e = 0,len(nums)-1
res = 0
@lru_cache(2000)
def dfs(ind,s,e):
if ind>=len(multipliers):
return 0
a = multipliers[ind]*nums[s] + dfs(ind+1,s+1,e)
b = multipliers[ind]*nums[e] + dfs(ind+1,s,e-1)
return max(a,b)
return dfs(0,s,e) | maximum-score-from-performing-multiplication-operations | ππ Well-coded || Simple & Concise || Memoization π | abhi9Rai | 1 | 229 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,415 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2584162/O(M2)-with-Iterative-DP-using-two-queues-(Example-Illustration) | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
n, m = len(nums), len(multipliers)
dp1, dp2 = [0] * (m+1), [0] * (m+1)
print("nums:", nums, "mul:", multipliers)
print("dp:", dp1)
for k in range(m-1,-1,-1):
for i in range(0, k+1):
dp2[i] = max(multipliers[k] * nums[i] + dp1[i+1], multipliers[k] * nums[(n-1)+i-k] + dp1[i])
dp1, dp2 = dp2, dp1
print("+ ", k, dp1)
ans = dp1[0]
print("ans:", ans)
print("="*20, "\n")
return ans
print = lambda *a, **aa: () | maximum-score-from-performing-multiplication-operations | O(M^2) with Iterative DP using two queues (Example Illustration) | dntai | 0 | 11 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,416 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2584162/O(M2)-with-Iterative-DP-using-two-queues-(Example-Illustration) | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
n, m = len(nums), len(multipliers)
def fsol(i, k):
if dp[i][k] is not None:
return dp[i][k]
r1 = multipliers[k] * nums[i]
r2 = multipliers[k] * nums[(n-1)+i-k]
if k<=m-2:
r1 = r1 + fsol(i+1, k+1)
r2 = r2 + fsol(i, k+1)
dp[i][k] = max(r1, r2)
return dp[i][k]
dp = [[None] * (m+1) for _ in range(m+1)]
ans = fsol(0, 0)
return ans | maximum-score-from-performing-multiplication-operations | O(M^2) with Iterative DP using two queues (Example Illustration) | dntai | 0 | 11 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,417 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2583652/python-efficient-and-short-solution-using-%40lru_cache | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
@lru_cache(2000)
def dynamic(st,end,idx):
if idx==len(multipliers)-1:
return max(nums[st]*multipliers[idx],nums[end]*multipliers[idx])
return max((nums[st]*multipliers[idx])+dynamic(st+1,end,idx+1),(nums[end]*multipliers[idx])+dynamic(st,end-1,idx+1))
return dynamic(0,len(nums)-1,0) | maximum-score-from-performing-multiplication-operations | python efficient and short solution using @lru_cache | benon | 0 | 55 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,418 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2582910/Python-Iterative-DP-solution-(Explained) | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
'''
Iterative DP coded in this way as it seems to be more intuitive in my opinion.
If still encountering problems understanding, trace through one or two simple testcases.
'''
# This dp list stores the maximum potential amount we can still get based on the number of operations done and left steps taken
# **Eg dp[n][m] stores the max amt we can still get after doing n operations and taking m left steps**
# Since there are 2 states, create a 2d list to store DP of number of ops done and number of left steps taken,
# with additional column and row to store base case of 0
dp = [[0] * (len(multipliers)+1) for _ in range(len(multipliers)+1)]
# Number of operations done at this point in time (working backwards!)
# Eg. if op = 2, then we have already completed 2 operations at this point
for op in range(len(multipliers)-1,-1,-1):
for left in range(op, -1, -1):
# Note:
# Number of left steps taken can never exceed number of operations.
# Also, number of right steps taken would be
# (number of operations done) - (number of left steps taken)
# Eg if you did 3 operations already and have taken 2 left steps, then it means you took 1 right step
right = op - left
# Find maximum of the 2 choices: Take left or right step?
# Left:
# If you take the left step, know that your max amount now is the current value obtained in this step,
# plus the potential amount you can get after this step,
# rmb you have done 1 more operation and taken 1 more left step
# Right:
# If you take the right step, the max amount now is the current value obtained in this step,
# plus the potential amount after this,
# rmb you have done 1 more operation but have taken 0 more left steps
dp[op][left] = max(multipliers[op]*nums[left] + dp[op+1][left+1],
multipliers[op]*nums[len(nums)-1-right] + dp[op+1][left]
)
return dp[0][0] # Maximum potential amount we can get after 0 operations done (and 0 left steps naturally) | maximum-score-from-performing-multiplication-operations | Python Iterative DP solution (Explained) | chkmcnugget | 0 | 20 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,419 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1712969/Python-Iterative-solution-in-O(M)-space-and-O(M2)-time | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
M = len(multipliers)
N = len(nums)
ind = M & 1
dp = [[0]*(M + 1) for _ in range(2)]
for mi in range(M - 1, -1, -1):
ind = mi & 1
prev = ind ^ 1
for i in range(mi+1):
j = N - mi + i - 1
start_value = dp[prev][i + 1] + nums[i] * multipliers[mi]
end_value = dp[prev][i] + nums[j] * multipliers[mi]
dp[ind][i] = max(start_value, end_value)
return dp[0][0] | maximum-score-from-performing-multiplication-operations | Python Iterative solution in O(M) space and O(M^2) time | atiq1589 | 0 | 206 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,420 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1615639/Help-finding-the-bug-in-my-solution.-Passes-4362-test-cases-then-fails | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
if len(nums) == 1:
return nums[0] * multipliers[0]
score = {}
# Initialize base cases
reversed_nums = list(reversed(nums))
left_sum = 0
right_sum = 0
for i in range(1, len(multipliers) + 1):
left_sum += nums[i-1] * multipliers[i-1]
right_sum += reversed_nums[i-1] * multipliers[i-1]
score.update({
(i, 0): left_sum,
(0, i): right_sum
})
# Build solutions
for lc in range(1, len(multipliers) + 1):
for rc in range(1, len(multipliers) + 1):
if lc + rc > len(multipliers):
break
new_score = max(score[(lc - 1, rc)] + multipliers[lc + rc - 1]*nums[lc - 1], score[(lc, rc - 1)] + multipliers[lc + rc - 1]*nums[len(nums) - rc] )
score[(lc, rc)] = new_score
import pprint
#pprint.pprint(score)
return max(score.values()) | maximum-score-from-performing-multiplication-operations | Help finding the bug in my solution. Passes 43/62 test cases then fails | newbieleetcoder | 0 | 91 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,421 |
https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1445128/Simple-Python-O(n2)-dynamic-programming-solution | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
m, n = len(multipliers), len(nums)
# let dp[i][j] denote the maximum score using the first i elements
# and last j elements from nums
dp = [[-float("inf")]*(m+1) for _ in range(m+1)]
# initialization, populate the first row and column of the
# dp table
dp[0][0] = 0
for i in range(1, m+1):
dp[i][0] = dp[i-1][0]+multipliers[i-1]*nums[i-1]
dp[0][i] = dp[0][i-1]+multipliers[i-1]*nums[-i]
# state transition, populate the dp table inward
# dp[n_left][n_right] = max(score if the last num used was from the left,
# score if the last num used was from the right)
ret = -float("inf")
for n_used in range(1, m+1):
for n_left in range(n_used+1):
n_right = n_used-n_left
dp[n_left][n_right] = max(dp[n_left-1][n_right]+multipliers[n_used-1]*nums[n_left-1],
dp[n_left][n_right-1]+multipliers[n_used-1]*nums[-n_right])
if n_used == m:
ret = max(ret, dp[n_left][n_right])
return ret | maximum-score-from-performing-multiplication-operations | Simple Python O(n^2) dynamic programming solution | Charlesl0129 | 0 | 293 | maximum score from performing multiplication operations | 1,770 | 0.366 | Hard | 25,422 |
https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/discuss/1075709/Python3-top-down-dp | class Solution:
def longestPalindrome(self, word1: str, word2: str) -> int:
@cache
def fn(lo, hi):
"""Return length of longest palindromic subsequence."""
if lo >= hi: return int(lo == hi)
if word[lo] == word[hi]: return 2 + fn(lo+1, hi-1)
return max(fn(lo+1, hi), fn(lo, hi-1))
ans = 0
word = word1 + word2
for x in ascii_lowercase:
i = word1.find(x)
j = word2.rfind(x)
if i != -1 and j != -1: ans = max(ans, fn(i, j + len(word1)))
return ans | maximize-palindrome-length-from-subsequences | [Python3] top-down dp | ye15 | 13 | 425 | maximize palindrome length from subsequences | 1,771 | 0.352 | Hard | 25,423 |
https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/discuss/1075551/Python-Dynamic-Programming-O((m%2Bn)2) | class Solution:
def longestPalindrome(self, word1: str, word2: str) -> int:
s1 = word1 + word2
n = len(s1)
dp = [[0] * n for i in range(n)]
ans = 0
for i in range(n-1,-1,-1):
# mark every character as a 1 length palindrome
dp[i][i] = 1
for j in range(i+1,n):
# new palindrome is found
if s1[i] == s1[j]:
dp[i][j] = dp[i+1][j-1] + 2
# if the palindrome includes both string consider it as a valid
if i < len(word1) and j >= len(word1):
ans = max(ans,dp[i][j])
else:
dp[i][j] = max(dp[i][j-1],dp[i+1][j])
return ans | maximize-palindrome-length-from-subsequences | [Python] Dynamic Programming O((m+n)^2) | skele | 4 | 208 | maximize palindrome length from subsequences | 1,771 | 0.352 | Hard | 25,424 |
https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/discuss/2446207/Python-3-simple-DP | class Solution:
def longestPalindrome(self, word1: str, word2: str) -> int:
res=0
new_word=word1+word2
n,mid=len(word1)+len(word2),len(word1)
dp=[[0]*n for _ in range(n)]
for i in range(n):
dp[i][i]=1
for l in range(n-2,-1,-1):
for r in range(l+1,n,1):
if new_word[l]==new_word[r]:
dp[l][r]=(dp[l+1][r-1] if r-1>=l+1 else 0)+2
if l<mid and r>=mid:
res=max(res,dp[l][r])
else:
dp[l][r]=max(dp[l+1][r],dp[l][r-1])
return res | maximize-palindrome-length-from-subsequences | [Python 3] simple DP | gabhay | 1 | 48 | maximize palindrome length from subsequences | 1,771 | 0.352 | Hard | 25,425 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1085906/Python-3-or-2-liner-or-Explanation | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
d = {'type': 0, 'color': 1, 'name': 2}
return sum(1 for item in items if item[d[ruleKey]] == ruleValue) | count-items-matching-a-rule | Python 3 | 2-liner | Explanation | idontknoooo | 46 | 3,200 | count items matching a rule | 1,773 | 0.843 | Easy | 25,426 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1085783/Python3-1-line | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
return sum(1 for t, c, n in items if (ruleKey, ruleValue) in (("type", t), ("color", c), ("name", n))) | count-items-matching-a-rule | [Python3] 1-line | ye15 | 23 | 2,100 | count items matching a rule | 1,773 | 0.843 | Easy | 25,427 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2269882/PYTHON-3-ONE-LINER | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
return sum(item_list[{"type": 0, "color": 1, "name": 2}[ruleKey]] == ruleValue for item_list in items) | count-items-matching-a-rule | [PYTHON 3] ONE LINER | omkarxpatel | 5 | 137 | count items matching a rule | 1,773 | 0.843 | Easy | 25,428 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1176074/Python3-simple-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
count = 0
a = ["type", "color", "name"]
x = a.index(ruleKey)
for i in range(len(items)):
if ruleValue == items[i][x]:
count += 1
return count | count-items-matching-a-rule | Python3 simple solution | EklavyaJoshi | 5 | 336 | count items matching a rule | 1,773 | 0.843 | Easy | 25,429 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2821411/PYTHON3 | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
d = {'type': 0, 'color': 1, 'name': 2}
return sum(1 for item in items if item[d[ruleKey]] == ruleValue) | count-items-matching-a-rule | PYTHON3 | Gurugubelli_Anil | 1 | 42 | count items matching a rule | 1,773 | 0.843 | Easy | 25,430 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2290787/python3-oror-easy-solution-oror-O(N) | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
valueToCheck=None
result=0
if ruleKey=='type':
valueToCheck=0
elif ruleKey=='color':
valueToCheck=1
elif ruleKey=='name':
valueToCheck=2
for i in items:
if i[valueToCheck]==ruleValue:
result+=1
return result | count-items-matching-a-rule | python3 || easy solution || O(N) | _soninirav | 1 | 60 | count items matching a rule | 1,773 | 0.843 | Easy | 25,431 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1726439/Count-Items-Matching-a-Rule-solution-python | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
count=0
var=0
if ruleKey=="type":
var=0
elif ruleKey=="color":
var=1
elif ruleKey=="name":
var=2
for x in items:
if x[var]==ruleValue:
count+=1
return count | count-items-matching-a-rule | Count Items Matching a Rule solution python | seabreeze | 1 | 122 | count items matching a rule | 1,773 | 0.843 | Easy | 25,432 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1386918/2-line-solution-in-Python | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
key_inedx = 0 if ruleKey == "type" else 1 if ruleKey == "color" else 2
return sum(item[key_inedx] == ruleValue for item in items) | count-items-matching-a-rule | 2-line solution in Python | mousun224 | 1 | 175 | count items matching a rule | 1,773 | 0.843 | Easy | 25,433 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1241425/Python3-two-line-solution-with-list-comprehension | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
key = 0 if ruleKey == "type" else 1 if ruleKey == "color" else 2
return len([item for item in items if item[key] == ruleValue]) | count-items-matching-a-rule | Python3 two line solution with list comprehension | albezx0 | 1 | 142 | count items matching a rule | 1,773 | 0.843 | Easy | 25,434 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1223362/easiest-code-in-python-or | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
a=['type','color', 'name']
b=a.index(ruleKey)
ans=0
for i in items:
if i[b] == ruleValue:
ans+=1
return ans | count-items-matching-a-rule | easiest code in python | | chikushen99 | 1 | 194 | count items matching a rule | 1,773 | 0.843 | Easy | 25,435 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1221389/220ms-Python-(with-comments) | class Solution(object):
def countMatches(self, items, ruleKey, ruleValue):
"""
:type items: List[List[str]]
:type ruleKey: str
:type ruleValue: str
:rtype: int
"""
#Create a variable to store the output
result = 0
#Convert the ruleKey into equivalent indexes
if ruleKey == 'type':
key = 0
elif ruleKey == 'color':
key = 1
else:
key = 2
#Loop through each of the list in the items list
for item in items:
#check if the appropriate value in each inner list at the respective location matches the ruleValue
if item[key] == ruleValue:
result += 1
return result | count-items-matching-a-rule | 220ms, Python (with comments) | Akshar-code | 1 | 78 | count items matching a rule | 1,773 | 0.843 | Easy | 25,436 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1158672/yet-another-python-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
rules = {
'type': 0,
'color': 1,
'name': 2
}
counter = 0
for val in items:
if val[rules[ruleKey]] == ruleValue:
counter += 1
return counter | count-items-matching-a-rule | yet another python solution | Landsknecht | 1 | 95 | count items matching a rule | 1,773 | 0.843 | Easy | 25,437 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1086719/PYTHON-VERY-SIMPLE-SOLUTION | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
ruleKeys=["type","color","name"]
ruleKeyIndex=ruleKeys.index(ruleKey)
c=0
for i in range(len(items)):
if items[i][ruleKeyIndex]==ruleValue:
c+=1
return c | count-items-matching-a-rule | PYTHON VERY SIMPLE SOLUTION β
| lokeshsenthilkumar | 1 | 260 | count items matching a rule | 1,773 | 0.843 | Easy | 25,438 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1085851/Python-Solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
counter = 0
for t, c, n in items:
if ruleKey == "type" and t == ruleValue:
counter += 1
if ruleKey == "color" and c == ruleValue:
counter += 1
if ruleKey == "name" and n == ruleValue:
counter += 1
return counter | count-items-matching-a-rule | Python Solution | mariandanaila01 | 1 | 142 | count items matching a rule | 1,773 | 0.843 | Easy | 25,439 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2847571/PYTHON-SIMPLE-AND-EASY | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
op = {"type":0,"color":1,"name":2}
search = op[ruleKey]
count = 0
for i in range(0,len(items)):
if ruleValue == items[i][search]:
count = count+1
return count | count-items-matching-a-rule | PYTHON SIMPLE AND EASY | ameenusyed09 | 0 | 1 | count items matching a rule | 1,773 | 0.843 | Easy | 25,440 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2800672/Simple-understandable-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
p=0
c=0
if ruleKey=='type':
c=0
elif ruleKey=='color':
c=1
else:
c=2
for j in range(len(items)):
g=items[j]
if g[c]==ruleValue:
p+=1
return p | count-items-matching-a-rule | Simple understandable solution | priyanshupriyam123vv | 0 | 1 | count items matching a rule | 1,773 | 0.843 | Easy | 25,441 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2783431/Simple-Python3-Solution-oror-Easy-and-Explained | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
count = 0
if ruleKey == "color":
b = 1
elif ruleKey == "type":
b = 0
else:
b = 2
for i in items:
if i[b] == ruleValue:
count = count + 1
return count | count-items-matching-a-rule | Simple Python3 Solution || Easy & Explained | dnvavinash | 0 | 2 | count items matching a rule | 1,773 | 0.843 | Easy | 25,442 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2782232/Python-Short-and-simple-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
d = {'type': 0, 'color': 1, 'name': 2}
ans, index = 0, d[ruleKey]
for i in items:
if i[index] == ruleValue:
ans += 1
return ans | count-items-matching-a-rule | [Python] Short and simple solution | Mark_computer | 0 | 3 | count items matching a rule | 1,773 | 0.843 | Easy | 25,443 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2781372/Python3-2-liner-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
d = {'type': 0, 'color': 1, 'name': 2}
return sum(1 for item in items if item[d[ruleKey]] == ruleValue) | count-items-matching-a-rule | Python3 2 liner solution | avs-abhishek123 | 0 | 1 | count items matching a rule | 1,773 | 0.843 | Easy | 25,444 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2745946/Simple-python-code-with-explanation | class Solution:
def countMatches(self, items, ruleKey, ruleValue):
#create a variable count to store the matching value
count = 0
#if the rulekey is "type"
if ruleKey == "type":
#then we need to check only first element in each sublist of items(list)
for i in range(len(items)):
#if that first value equal to rule value
if items[i][0] == ruleValue:
#then increase the count value by 1
count += 1
#if the rulekey is "color"
elif ruleKey == "color":
#then we need to check only second element in each sublist of items(list)
for i in range(len(items)):
#if the second value equal to rule value
if items[i][1] == ruleValue:
#then increase the count value by 1
count+=1
#if the rulekey is "name"
elif ruleKey == "name":
#then we need to check only third element in each sublist of items(list)
for i in range(len(items)):
#if the third value equal to rule value
if items[i][2] == ruleValue:
#then increase the count value by 1
count+=1
#after checking all if statements
#return count value
return count | count-items-matching-a-rule | Simple python code with explanation | thomanani | 0 | 5 | count items matching a rule | 1,773 | 0.843 | Easy | 25,445 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2739521/Python-solution(faster-than-80) | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
rule_keys = {'type': 0, 'color': 1, 'name': 2}
count = 0
for i in items:
if i[rule_keys[ruleKey]] == ruleValue:
count += 1
return count | count-items-matching-a-rule | Python solution(faster than 80%) | iakylbek | 0 | 5 | count items matching a rule | 1,773 | 0.843 | Easy | 25,446 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2670043/Python3-one-line-solution-beats-85-98 | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
return sum([x[{'type': 0, 'color': 1, 'name': 2}[ruleKey]]==ruleValue for x in items]) | count-items-matching-a-rule | Python3 one-line solution - beats 85% / 98% | sipi09 | 0 | 3 | count items matching a rule | 1,773 | 0.843 | Easy | 25,447 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2616737/Count-Items-Matching-a-Rule | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
count = 0
if ruleKey == 'type':
k = 0
elif ruleKey == 'color':
k = 1
else :
k = 2
for i in range(len(items)):
if items[i][k] == ruleValue:
count += 1
return count | count-items-matching-a-rule | Count Items Matching a Rule | PravinBorate | 0 | 10 | count items matching a rule | 1,773 | 0.843 | Easy | 25,448 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2490639/Python-or-2-Different-Solutions-or-Optimal-Complexity | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
# Method 1: T.C: O(n) S.C: O(1)
ans = 0
if ruleKey == "type":
check = 0
elif ruleKey == "color":
check = 1
else:
check = 2
for i in range(len(items)):
if items[i][check] == ruleValue:
ans += 1
return ans
# Method 2(Dictionary): T.C: O(n) S.C: O(1)
d = {'type': 0, 'color': 1, 'name': 2}
ans = 0
for item in items:
if item[d[ruleKey]] == ruleValue:
ans += 1
return ans
# Search with tag chawlashivansh for my solutions. | count-items-matching-a-rule | Python | 2 Different Solutions | Optimal Complexity | chawlashivansh | 0 | 19 | count items matching a rule | 1,773 | 0.843 | Easy | 25,449 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2473492/Simple-hash-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
res = 0
dic = {"type": 0,
"color": 1,
"name":2,
}
for item in items:
if item[dic[ruleKey]] == ruleValue:
res += 1
return res | count-items-matching-a-rule | Simple hash solution | aruj900 | 0 | 24 | count items matching a rule | 1,773 | 0.843 | Easy | 25,450 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2424522/Brute-Force-Approach-(-Easy-Python-Solution-) | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
t,c,n = [],[],[]
for i in items:
for j in i:
if ruleKey == "type":
t.append(i[0])
if ruleKey == "color":
c.append(i[1])
if ruleKey == "name":
n.append(i[2])
r = []
if ruleKey == "type":
l = t
if ruleKey == "color":
l = c
if ruleKey == "name":
l = n
for k in range(0,len(l),3):
if ruleKey == "type":
r.append(t[k])
if ruleKey == "color":
r.append(c[k])
if ruleKey == "name":
r.append(n[k])
return (r.count(ruleValue)) | count-items-matching-a-rule | Brute Force Approach ( Easy Python Solution ) | SouravSingh49 | 0 | 32 | count items matching a rule | 1,773 | 0.843 | Easy | 25,451 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2258218/Count-Items-Matching-a-Rule | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
out = 0
KeyIndex=0
if ruleKey=="color":
KeyIndex=1
if ruleKey=="type":
KeyIndex=0
if ruleKey=="name":
KeyIndex=2
for i in items:
if i[KeyIndex]==ruleValue:
out+=1
return out | count-items-matching-a-rule | Count Items Matching a Rule | dhananjayaduttmishra | 0 | 20 | count items matching a rule | 1,773 | 0.843 | Easy | 25,452 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2229705/Beginner-Friendly-Solution-oror-Python | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
count = 0
# Edge Case: ruleKey is neither of the required strings.
# In such a case, this block of code prevents the for-loop from running needlessly, thus reducing runtime and memory uptake.
if ruleKey not in ['type', 'color', 'name']:
return count
for i in items:
if ruleKey == 'type' and i[0] == ruleValue:
count += 1
elif ruleKey == 'color' and i[1] == ruleValue:
count += 1
elif ruleKey == 'name' and i[2] == ruleValue:
count += 1
return count | count-items-matching-a-rule | Beginner Friendly Solution || Python | cool-huip | 0 | 31 | count items matching a rule | 1,773 | 0.843 | Easy | 25,453 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2187352/Python-3.10-Switch-Case-based-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
matching_items_count = 0
for item in items:
match ruleKey:
case "type":
if item[0] == ruleValue:
matching_items_count += 1
case "color":
if item[1] == ruleValue:
matching_items_count += 1
case "name":
if item[2] == ruleValue:
matching_items_count += 1
return matching_items_count | count-items-matching-a-rule | Python 3.10 Switch Case -based solution | tonimobin | 0 | 15 | count items matching a rule | 1,773 | 0.843 | Easy | 25,454 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2147891/python-or-easy-solution-for-beginners | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
c=0
for i in range(len(items)):
if ruleKey=="type":
if items[i][0]==ruleValue:
c+=1
if ruleKey=="color":
if items[i][1]==ruleValue:
c+=1
if ruleKey=="name":
if items[i][2]==ruleValue:
c+=1
return c | count-items-matching-a-rule | python | easy solution for beginners | T1n1_B0x1 | 0 | 56 | count items matching a rule | 1,773 | 0.843 | Easy | 25,455 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2075866/O(N)-basic-list-comp | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
keys = ["type", "color", "name"]
i = keys.index(ruleKey)
return sum([1 if item[i] == ruleValue else 0 for item in items]) | count-items-matching-a-rule | O(N) basic list comp | andrewnerdimo | 0 | 41 | count items matching a rule | 1,773 | 0.843 | Easy | 25,456 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2040881/Python3-simple-code | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
rules = ["type", "color", "name"]
count = 0
for item in items:
if item[rules.index(ruleKey)] == ruleValue:
count += 1
return count | count-items-matching-a-rule | [Python3] simple code | Shiyinq | 0 | 55 | count items matching a rule | 1,773 | 0.843 | Easy | 25,457 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2014004/Easy-Python-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
res = 0
for i, (types, color, name) in enumerate(items):
if ruleKey == 'color':
if color == ruleValue:
res += 1
elif ruleKey == 'type':
if types == ruleValue:
res += 1
else:
if name == ruleValue:
res += 1
return res | count-items-matching-a-rule | Easy Python solution | ankurbhambri | 0 | 72 | count items matching a rule | 1,773 | 0.843 | Easy | 25,458 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2000621/Python-Clean-and-Simple! | class Solution:
def countMatches(self, items, ruleKey, ruleValue):
ruleMap = {"type":0, "color":1, "name":2}
return len(list(filter(lambda x : x[ruleMap[ruleKey]] == ruleValue, items))) | count-items-matching-a-rule | Python - Clean and Simple! | domthedeveloper | 0 | 76 | count items matching a rule | 1,773 | 0.843 | Easy | 25,459 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/2000621/Python-Clean-and-Simple! | class Solution:
def countMatches(self, items, ruleKey, ruleValue):
ruleMap = {"type":0, "color":1, "name":2}
return sum(item[ruleMap[ruleKey]] == ruleValue for item in items) | count-items-matching-a-rule | Python - Clean and Simple! | domthedeveloper | 0 | 76 | count items matching a rule | 1,773 | 0.843 | Easy | 25,460 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1910541/Python-Solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
index = ((2, 1)[ruleKey == 'color'], 0)[ruleKey == 'type']
return len(list(filter(lambda x: x[index] == ruleValue, items))) | count-items-matching-a-rule | Python Solution | hgalytoby | 0 | 60 | count items matching a rule | 1,773 | 0.843 | Easy | 25,461 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1910541/Python-Solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
index = {'type': 0, 'color': 1, 'name': 2}
return len(list(filter(lambda x: x[index[ruleKey]] == ruleValue, items))) | count-items-matching-a-rule | Python Solution | hgalytoby | 0 | 60 | count items matching a rule | 1,773 | 0.843 | Easy | 25,462 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1873846/Python-(Using-Dict) | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
marker = {'type':0, 'color':1, 'name':2}
count=0
for i in items:
if i[marker[ruleKey]]==ruleValue:
count+=1
return count | count-items-matching-a-rule | Python (Using Dict) | sharma_nayaab | 0 | 38 | count items matching a rule | 1,773 | 0.843 | Easy | 25,463 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1793692/PYTHON-or-Other-dictionnary-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
dic={"type":[],
"color":[],
"name":[]}
ans = 0
for i in range(len(items)):
for j in range(len(dic)):
if j == 0 :
dic["type"].append(items[i][j])
elif j == 1:
dic["color"].append(items[i][j])
elif j == 2:
dic["name"].append(items[i][j])
for i in range(len(items)):
if ruleValue == dic[ruleKey][i]:
ans+=1
return ans | count-items-matching-a-rule | PYTHON | Other dictionnary solution | Noyha | 0 | 28 | count items matching a rule | 1,773 | 0.843 | Easy | 25,464 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1754087/Quite-simple-and-fast | class Solution:
def countMatches(self, items: List[List[str]], rK: str, rV: str) -> int:
cnt=0
d = {"type":0, "color":1, "name":2}
for i in range(len(items)):
if items[i][d[rK]] == rV:
cnt += 1
return cnt | count-items-matching-a-rule | Quite simple and fast | flame91 | 0 | 42 | count items matching a rule | 1,773 | 0.843 | Easy | 25,465 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1753853/Python-Solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
rule = {'type':0, 'color':1, 'name':2}
count = 0
for i in items:
idx = rule[ruleKey]
if i[idx] == ruleValue:
count += 1
return count | count-items-matching-a-rule | Python Solution | MengyingLin | 0 | 53 | count items matching a rule | 1,773 | 0.843 | Easy | 25,466 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1709422/Python3-accepted-solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
keyval = {"type":0,"color":1,"name":2}
return ([i[list(keyval.keys()).index(ruleKey)] for i in items].count(ruleValue)) | count-items-matching-a-rule | Python3 accepted solution | sreeleetcode19 | 0 | 45 | count items matching a rule | 1,773 | 0.843 | Easy | 25,467 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1699770/Python-Simple-Solution | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
dic ={ "type":0, "color":1, "name":2 }
var = 0
for i in items:
if i[dic[ruleKey]] == ruleValue:
var += 1
return var | count-items-matching-a-rule | Python Simple Solution | vijayvardhan6 | 0 | 61 | count items matching a rule | 1,773 | 0.843 | Easy | 25,468 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1647931/Easy-Python3-solution-faster-than-98 | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
res = []
for i in range(len(items)):
if ruleKey == "type" and ruleValue == items[i][0]:
res.append(items[i])
elif ruleKey == "color" and ruleValue == items[i][1]:
res.append(items[i])
elif ruleKey == "name" and ruleValue == items[i][2]:
res.append(items[i])
return len(res) | count-items-matching-a-rule | Easy Python3 solution - faster than 98% | y-arjun-y | 0 | 82 | count items matching a rule | 1,773 | 0.843 | Easy | 25,469 |
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1642127/Easy-To-Understand-Python-Solution-Faster-Than-100 | class Solution(object):
def countMatches(self, items, ruleKey, ruleValue):
output = 0
itemsi = ["type","color","name"]
ruleKey = itemsi.index(ruleKey)
for i in items:
if i[ruleKey] == ruleValue:
output += 1
return output | count-items-matching-a-rule | Easy To Understand Python Solution Faster Than 100% | yparikh | 0 | 110 | count items matching a rule | 1,773 | 0.843 | Easy | 25,470 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1085820/Python3-top-down-dp | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
toppingCosts *= 2
@cache
def fn(i, x):
"""Return sum of subsequence of toppingCosts[i:] closest to x."""
if x < 0 or i == len(toppingCosts): return 0
return min(fn(i+1, x), toppingCosts[i] + fn(i+1, x-toppingCosts[i]), key=lambda y: (abs(y-x), y))
ans = inf
for bc in baseCosts:
ans = min(ans, bc + fn(0, target - bc), key=lambda x: (abs(x-target), x))
return ans | closest-dessert-cost | [Python3] top-down dp | ye15 | 18 | 3,000 | closest dessert cost | 1,774 | 0.468 | Medium | 25,471 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1085820/Python3-top-down-dp | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
@cache
def fn(i, cost):
"""Return sum of subsequence closest to target."""
if cost >= target or i == len(toppingCosts): return cost
return min(fn(i+1, cost), fn(i+1, cost+toppingCosts[i]), key=lambda x: (abs(x-target), x))
ans = inf
toppingCosts *= 2
for cost in baseCosts:
ans = min(ans, fn(0, cost), key=lambda x: (abs(x-target), x))
return ans | closest-dessert-cost | [Python3] top-down dp | ye15 | 18 | 3,000 | closest dessert cost | 1,774 | 0.468 | Medium | 25,472 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1085820/Python3-top-down-dp | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
top = {0}
for x in toppingCosts*2:
top |= {x + xx for xx in top}
top = sorted(top)
ans = inf
for bc in baseCosts:
k = bisect_left(top, target - bc)
if k < len(top): ans = min(ans, bc + top[k], key=lambda x: (abs(x-target), x))
if k: ans = min(ans, bc + top[k-1], key=lambda x: (abs(x-target), x))
return ans | closest-dessert-cost | [Python3] top-down dp | ye15 | 18 | 3,000 | closest dessert cost | 1,774 | 0.468 | Medium | 25,473 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1818264/Python-or-BFS-or-207ms-or-4-line-or-fast-and-simple-solution | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
q = [target - basecost for basecost in baseCosts]
for toppingcost in toppingCosts:
q += [val - cost for val in q if val > 0 for cost in (toppingcost, toppingcost * 2)]
return target - min(q, key=lambda x: abs(x) * 2 - (x > 0)) | closest-dessert-cost | Python | BFS | 207ms | 4-line | fast and simple solution | xuauul | 5 | 198 | closest dessert cost | 1,774 | 0.468 | Medium | 25,474 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1087622/Backtracking(%2Bmemo)-with-comments | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
self.cost = baseCosts[0]
# my trick here: double the toppings list since each topping can only be used at most twice -- so I don't need to care about this restriction down the road
toppings = toppingCosts + toppingCosts
# toppingIdx: point to current topping
# used: cost of picked items (base + topping)
@lru_cache(None)
def dfs(toppingIdx, used):
# base case
if used > target:
# update if closer
if used - target < abs(self.cost - target):
self.cost = used
# end here since used is already exceed target
return
# update if closer
if target - used <= abs(self.cost - target):
self.cost = used
# reach end of the topping list
if toppingIdx == len(toppings):
return
# move onto next
# pick current item
dfs(toppingIdx+1, used+toppings[toppingIdx])
# skip current item
dfs(toppingIdx+1, used)
# try out different base
for base in baseCosts:
dfs(0, base)
return self.cost | closest-dessert-cost | Backtracking(+memo) with comments | w_x | 3 | 263 | closest dessert cost | 1,774 | 0.468 | Medium | 25,475 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1085928/Python-3-or-Backtracking-DFS-or-Explanation | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
m = len(toppingCosts)
ans = (baseCosts[0], abs(baseCosts[0]-target), -1 if target > baseCosts[0] else (0 if target == baseCosts[0] else 1))
def dfs(cnt, cur_idx):
nonlocal ans, m, base
if cur_idx >= m: return
for i in range(3):
cnt[cur_idx] = i
if cur_idx >= m: return
s = sum([tc * c for tc, c in zip(toppingCosts, cnt)]) + base
diff = abs(target - s)
sign = -1 if target > s else (0 if target == s else 1)
if not diff: ans = (target, 0, 0); return
if diff < ans[1]: ans = (s, diff, sign)
elif diff == ans[1] and ans[2] == 1 and sign == -1: ans = (s, diff, sign)
dfs(cnt[:], cur_idx+1)
for base in baseCosts:
dfs([0] * m, 0)
return ans[0] | closest-dessert-cost | Python 3 | Backtracking, DFS | Explanation | idontknoooo | 3 | 279 | closest dessert cost | 1,774 | 0.468 | Medium | 25,476 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1086226/Python-or-Backtracking-or-Simple | class Solution:
def bt(self, index, stack):
if index>=len(self.toppingCosts):
if self.minDiff>abs(self.target-sum(stack)):
self.minDiff= abs(self.target-sum(stack))
self.resStack=stack
return
for i in range(3):
self.bt(index+1, stack+[i*self.toppingCosts[index]])
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
self.resStack=[]
self.target= target
self.minDiff = float('inf')
self.toppingCosts= toppingCosts
for i in range(len(baseCosts)):
self.bt(0, [baseCosts[i]])
return sum(self.resStack) | closest-dessert-cost | Python | Backtracking | Simple | sarangvasishth | 2 | 231 | closest dessert cost | 1,774 | 0.468 | Medium | 25,477 |
https://leetcode.com/problems/closest-dessert-cost/discuss/2147526/Python-3-solution%3A-Minimizing-the-error-using-backtracking | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
toppingCosts *= 2
best_error = float("inf") # best error can be greater than `target`
@cache
def findError(index, target):
if index == len(toppingCosts):
return target
elif target < 0:
return target
return min(findError(index + 1, target - toppingCosts[index]),
findError(index + 1, target), key = lambda x : (abs(x), -x))
for base in baseCosts:
err = findError(0, target - base)
best_error = min(best_error, err, key = lambda x: (abs(x), -x))
return target - best_error | closest-dessert-cost | Python 3 solution: Minimizing the error using backtracking | goelujjwal | 1 | 152 | closest dessert cost | 1,774 | 0.468 | Medium | 25,478 |
https://leetcode.com/problems/closest-dessert-cost/discuss/2793047/Python3-or-Recursion-or-Explanation | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
def dfs(ind,cost):
nonlocal diff,ans
if diff > abs(target - cost):
diff = abs(target - cost)
ans = cost
elif diff == abs(target - cost):
if ans > cost:
ans = cost
if ind == m:
return 0
op1 = dfs(ind+1,cost)
op2 = dfs(ind+1,cost+toppingCosts[ind])
op3 = dfs(ind+1,cost+toppingCosts[ind]*2)
n,m = len(baseCosts),len(toppingCosts)
ans = 0
diff = math.inf
for i in range(n):
dfs(0,baseCosts[i])
return ans | closest-dessert-cost | [Python3] | Recursion | Explanation | swapnilsingh421 | 0 | 5 | closest dessert cost | 1,774 | 0.468 | Medium | 25,479 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1919472/Just-a-simple-Recursion | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
self.s=set()
n=len(toppingCosts)
for i in range(n):
toppingCosts.append(toppingCosts[i])
@lru_cache(None)
def rec(price,i):
self.s.add(price)
if i>=len(toppingCosts):
return
rec(price+toppingCosts[i],i+1)
rec(price,i+1)
for a in baseCosts:
rec(a,0)
mini=float('inf')
for a in self.s:
if abs(a-target)<mini:
if target-a>0:
mini=abs(a-target)
f=0
elif target-a<0:
mini=abs(a-target)
f=1
else:
return target
elif abs(a-target)==mini:
if target-a>0:
mini=abs(a-target)
f=0
if f==0:
return target-mini
else:
return target+mini | closest-dessert-cost | Just a simple Recursion | pbhuvaneshwar | 0 | 63 | closest dessert cost | 1,774 | 0.468 | Medium | 25,480 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1086228/python3-recursion-solution-for-reference | class Solution:
def closestCost(self, baseCosts, toppingCosts, target: int) -> int:
def toppings_r(toppings, rollingCost, targetCost, index, output):
if index >= len(toppings):
return
sc = rollingCost + toppings[index]
dc = sc + toppings[index]
oabs = abs(targetCost - output[-1])
if abs(rollingCost - targetCost) < oabs:
output[-1] = rollingCost
if abs(sc-targetCost) < oabs:
output[-1] = sc
if abs(dc-targetCost) < oabs:
output[-1] = dc
toppings_r(toppings, rollingCost, targetCost, index+1, output)
toppings_r(toppings, rollingCost + toppings[index], targetCost, index+1, output)
toppings_r(toppings, rollingCost + (2*toppings[index]),targetCost, index+1, output)
res = float('-inf')
output = [min(baseCosts)]
for base_cost in baseCosts:
toppings_r(toppingCosts, base_cost, target, 0, output)
if abs(res-target) > abs(output[-1]-target):
res = output[-1]
return res | closest-dessert-cost | python3 recursion - solution for reference | vadhri_venkat | 0 | 60 | closest dessert cost | 1,774 | 0.468 | Medium | 25,481 |
https://leetcode.com/problems/closest-dessert-cost/discuss/1085931/Python-top-down-dp-30ms | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
@lru_cache(None)
def dp(t, i):
if t <= 0 or i == len(toppingCosts):
return t
useOne = dp(t - toppingCosts[i], i + 1)
if useOne == 0:
return 0
useTwo = dp(t - toppingCosts[i] * 2, i + 1)
if useTwo == 0:
return 0
useNone = dp(t, i + 1)
if useNone == 0:
return 0
minimum = min((abs(useOne), -useOne), (abs(useTwo), -useTwo), (abs(useNone), -useNone))
return -minimum[1]
minimum = float('inf')
for b in baseCosts:
toFind = target - b
res = b + toFind - dp(toFind, 0)
minimum = min((abs(target - minimum), minimum), (abs(target - res), res))[1]
if minimum == target:
return minimum
return minimum | closest-dessert-cost | Python top-down dp 30ms | tyohekim | 0 | 65 | closest dessert cost | 1,774 | 0.468 | Medium | 25,482 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/1085806/Python3-two-heaps | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
if 6*len(nums1) < len(nums2) or 6*len(nums2) < len(nums1): return -1 # impossible
if sum(nums1) < sum(nums2): nums1, nums2 = nums2, nums1
s1, s2 = sum(nums1), sum(nums2)
nums1 = [-x for x in nums1] # max-heap
heapify(nums1)
heapify(nums2)
ans = 0
while s1 > s2:
x1, x2 = nums1[0], nums2[0]
if -1-x1 > 6-x2: # change x1 to 1
s1 += x1 + 1
heapreplace(nums1, -1)
else:
s2 += 6 - x2
heapreplace(nums2, 6)
ans += 1
return ans | equal-sum-arrays-with-minimum-number-of-operations | [Python3] two heaps | ye15 | 18 | 848 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,483 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/1085806/Python3-two-heaps | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
if 6*len(nums1) < len(nums2) or 6*len(nums2) < len(nums1): return -1 # impossible
if sum(nums1) < sum(nums2): nums1, nums2 = nums2, nums1
s1, s2 = sum(nums1), sum(nums2) # s1 >= s2
nums1.sort()
nums2.sort()
ans = j = 0
i = len(nums1)-1
while s1 > s2:
if j >= len(nums2) or 0 <= i and nums1[i] - 1 > 6 - nums2[j]:
s1 += 1 - nums1[i]
i -= 1
else:
s2 += 6 - nums2[j]
j += 1
ans += 1
return ans | equal-sum-arrays-with-minimum-number-of-operations | [Python3] two heaps | ye15 | 18 | 848 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,484 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/1085956/Python-3-or-Heap-Greedy-or-Explanations | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
s1, s2 = sum(nums1), sum(nums2)
if s1 > s2:
s1, s2 = s2, s1
nums1, nums2 = nums2, nums1
# to make s1 < s2
heapq.heapify(nums1)
nums2 = [-num for num in nums2]
heapq.heapify(nums2)
ans = 0
diff = s2 - s1
while diff > 0 and nums1 and nums2:
a = 6 - nums1[0]
b = - (1 + nums2[0])
if a > b:
heapq.heappop(nums1)
diff -= a
else:
heapq.heappop(nums2)
diff -= b
ans += 1
while diff > 0 and nums1:
a = 6 - heapq.heappop(nums1)
diff -= a
ans += 1
while diff > 0 and nums2:
b = - (1 + heapq.heappop(nums2))
diff -= b
ans += 1
return ans if diff <= 0 else -1 | equal-sum-arrays-with-minimum-number-of-operations | Python 3 | Heap, Greedy | Explanations | idontknoooo | 10 | 671 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,485 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/1088875/Priority-Queue-with-comments-(beat-100-when-posting) | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
# make sure nums1 has the larger sum
highSum, lowSum = sum(nums1), sum(nums2)
if highSum == lowSum:
return 0
if highSum < lowSum:
nums1, nums2 = nums2, nums1
highSum, lowSum = lowSum, highSum
# push nums1 into max heap
# push nums2 into min heap
maxHeap = []
for num in nums1:
heapq.heappush(maxHeap, -num)
minHeap = []
for num in nums2:
heapq.heappush(minHeap, num)
count = 0
while highSum != lowSum:
count += 1
diff = highSum - lowSum
high = -maxHeap[0]
low = minHeap[0]
# pick the biggest change
hightDelta = high - 1
lowDelta = 6 - low
# end case -- impossible
if hightDelta == lowDelta == 0:
return -1
if hightDelta >= lowDelta:
if hightDelta >= diff:
break
else:
# update sum and heap after change
heapq.heapreplace(maxHeap, -1)
highSum -= hightDelta
else:
if lowDelta >= diff:
break
else:
# update sum and heap after change
heapq.heapreplace(minHeap, 6)
lowSum += lowDelta
return count | equal-sum-arrays-with-minimum-number-of-operations | Priority Queue with comments (beat 100% when posting) | w_x | 3 | 172 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,486 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/1085880/Python-O(n)-time-O(1)-space-Greedy | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
A, B = nums1, nums2
sum_a, sum_b = sum(A), sum(B)
if sum_a > sum_b:
# keep sum(B) > sum(A)
A, B = B, A
sum_a, sum_b = sum_b, sum_a
# get element frequencies
freq_A, freq_B = [0] * 7, [0] * 7
for a in A:
freq_A[a] += 1
for b in B:
freq_B[b] += 1
# make sure it's possible
na, nb = len(A), len(B)
min_a, max_a = na, 6 * na
min_b, max_b = nb, 6 * nb
if min_a > max_b or min_b > max_a:
return -1
elif sum_a == sum_b:
return 0
# get number of equivalent difference-reducing operations available
num_ops_by_distance = [0] * 6
for elem in range(1, 7):
# element A[i] can be increased by up to (6 - A[i])
num_ops_by_distance[6 - elem] += freq_A[elem]
# element B[i] can be decreased by up to (B[i] - 1)
num_ops_by_distance[elem - 1] += freq_B[elem]
diff = sum_b - sum_a
res = 0
# decrease diff = sum(B) - sum(A) by largest remaining incr/decrements of size delta
for delta in range(5, 0, -1):
max_reduction = num_ops_by_distance[delta] * delta
if diff >= max_reduction:
# all incr/decrements of size delta are not enough to bridge the remaining difference
res += num_ops_by_distance[delta]
diff -= max_reduction
if diff <= 0:
break
else:
# get the actual number of operations needed for changes of given size delta
num_ops_needed, rem = divmod(diff, delta)
num_ops_needed += (rem > 0)
res += num_ops_needed
break
return res | equal-sum-arrays-with-minimum-number-of-operations | [Python] O(n) time O(1) space Greedy | geordgez | 3 | 392 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,487 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/1546613/python3-2-pointers-after-sorting-w-comments | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
# idea is to decrement values the array having larger sum and increment values in the array having small sum
# choose biggest element always to decrement values in large_sum_array
# choose smallest element always to increment values in small_sum_array
# both above points suggest , to have sorted arrays for better selection
# Now , once you get to this point , we need to select whether to decrement or increment in either of array for that
# we need to check which one in either of them , making differnece smaller and select that
sum1 = sum(nums1)
sum2 = sum(nums2)
if sum1 == sum2: # if sum is same , nothing is needed
return 0
# sort arrays , that will help in selecting elements in sorted order
nums1.sort()
nums2.sort()
# below is needed to make the code is simple
if sum1 > sum2:
larger_sum_array , smaller_sum_array = nums1 , nums2
else:
larger_sum_array , smaller_sum_array = nums2 , nums1
# normal initialization
largeSum = sum(larger_sum_array)
smallSum = sum(smaller_sum_array)
largeSumArrayLen = len(larger_sum_array)
smallSumArrayLen = len(smaller_sum_array)
left,right = 0, largeSumArrayLen-1
count = 0
diff = largeSum - smallSum
# we will have 2 pointer , right will iterate over large_sum_array for decreasing, biggest element
# left will iterate over small_sum_array for incrementing, smallest element
# once you see, which way is better minimizing diff of 2 arrays , move pointers accordingly
while left < smallSumArrayLen and right >= 0:
diffIfDecrement = diff - (larger_sum_array[right]-1) # value if you decide on decrement in largest sum array
diffIfIncrement = diff - (6-smaller_sum_array[left]) # value if you decide on increment in small_sum_array
if diffIfIncrement < diffIfDecrement: # selection which way is better i.e. who minimizes the diff better
smallSum += (6-smaller_sum_array[left])
left +=1
else:
largeSum -= (larger_sum_array[right]-1)
right -=1
count +=1
diff = largeSum - smallSum
if diff <=0: # point where largeSum is going down => suggests that point where sum can be equal
return count
while left < smallSumArrayLen: # largest_sum_array exhausted , only way is increment in small_sum_array
smallSum += (6-smaller_sum_array[left])
left +=1
count +=1
diff = largeSum - smallSum
if diff <=0: # point where largeSum is going down => suggests that point where sum can be equal
return count
while right > 0: # small_sum+array exhausted , only way is decrement in larget_sum_array
largeSum -= (larger_sum_array[right]-1)
right -=1
count +=1
diff = largeSum - smallSum
if diff <=0:# point where largeSum is going down => suggests that point where sum can be equal
return count
return -1 # sorry , you could not make them equal``` | equal-sum-arrays-with-minimum-number-of-operations | python3 , 2 pointers after sorting w/ comments | Code-IQ7 | 2 | 239 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,488 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/2824971/Python-solution-with-math-check | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
lDiv = len(nums1) / len(nums2)
if lDiv > 6 or lDiv < 1/6:
return -1
s1, s2 = sum(nums1), sum(nums2)
if s1 < s2:
s1, s2, nums1, nums2 = s2, s1, nums2, nums1
adjustments = [num - 1 for num in nums1]
adjustments += [6 - num for num in nums2]
adjustments.sort(reverse= True)
ops = 0
while s1 > s2:
s1 -= adjustments[ops]
ops += 1
return ops | equal-sum-arrays-with-minimum-number-of-operations | Python solution with math check | WhyYouCryingMama | 0 | 4 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,489 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/2637826/Python-O(n)-solution-easy-understanding | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
min_arr_size = len(nums1) if len(nums1)< len(nums2) else len(nums2)
max_arr_size = len(nums1) if len(nums1)>= len(nums2) else len(nums2)
# return -1 , if the biggest sum of shorter array is smaller than the smallest sum of longer one
if min_arr_size*6 < max_arr_size:
return -1
nums1_sum = sum(nums1)
nums2_sum = sum(nums2)
dis = abs(nums1_sum- nums2_sum)
# calculate each step size
steps = []
if nums1_sum > nums2_sum:
steps += [i-1 for i in nums1] + [6-i for i in nums2]
else:
steps += [i-1 for i in nums2] + [6-i for i in nums1]
# need to do operation from the biggest step
steps.sort(reverse = True)
cnt = 0
while dis > 0:
dis -= steps[cnt]
cnt+=1
return cnt | equal-sum-arrays-with-minimum-number-of-operations | Python O(n) solution, easy understanding | yu-che | 0 | 40 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,490 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/2554202/Python3-or-Priority-Queue-or-O(nlogn) | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
if len(nums1)>6*len(nums2) or len(nums2)>6*len(nums1):
return -1
s1,s2=sum(nums1),sum(nums2)
pq=[]
cnt=0
if s1==s2:
return cnt
if s1<s2:
nums1,nums2=nums2,nums1
s1,s2=s2,s1
diff=s1-s2
for v in nums1:
heappush(pq,-(v-1))
for v in nums2:
heappush(pq,-(6-v))
while diff>0:
curr=heappop(pq)
diff-=-curr
cnt+=1
return cnt | equal-sum-arrays-with-minimum-number-of-operations | [Python3] | Priority Queue | O(nlogn) | swapnilsingh421 | 0 | 79 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,491 |
https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/1086804/Python-with-Comments | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
# Get the delta
# We want sum(nums1) > sum(nums2) so we can use logic below
delta = sum(nums1) - sum(nums2)
if delta < 0:
nums1, nums2 = nums2, nums1
delta = -delta
# Dumb edge case
if delta == 0: return 0
# Their ranges do not overlap, impossible to return result
if len(nums1)*1 > len(nums2)*6: return -1
# Calculate the max subtractions
max_subtract = collections.defaultdict(int)
for i in nums1: max_subtract[i-1] += 1
for j in nums2: max_subtract[6-j] += 1
# Greedily subtract from delta
result = 0
for val, count in sorted(max_subtract.items(), key = lambda x: x[0], reverse=True):
for _ in range(count):
delta -= min(val, delta)
result += 1
if delta == 0:
return result
return result | equal-sum-arrays-with-minimum-number-of-operations | Python with Comments | dev-josh | 0 | 120 | equal sum arrays with minimum number of operations | 1,775 | 0.527 | Medium | 25,492 |
https://leetcode.com/problems/car-fleet-ii/discuss/1557743/Python3-Stack-Time%3A-O(n)-and-Space%3A-O(n) | class Solution:
def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:
# Stack: go from back and use stack to get ans
# Time: O(n)
# Space: O(n)
stack = [] # index
ans = [-1] * len(cars)
for i in range(len(cars)-1,-1,-1):
# remove cars that are faster than current car since it will never collide
while stack and cars[i][1] <= cars[stack[-1]][1]:
stack.pop()
while stack: # if car left, we can compute collide time with current car.
collision_t = (cars[stack[-1]][0] - cars[i][0]) / (cars[i][1] - cars[stack[-1]][1])
# if current car's collide time is greater than previous car's collide time
# (previous collided before current), then we have to find previous car's previous car
# to compute collide time with that car, so we pop from stack and re-process
# Otherwise, we add that collide time to answer and break
if ans[stack[-1]] == -1 or collision_t <= ans[stack[-1]]:
ans[i] = collision_t
break
stack.pop()
stack.append(i)
return ans | car-fleet-ii | [Python3] Stack - Time: O(n) & Space: O(n) | jae2021 | 4 | 261 | car fleet ii | 1,776 | 0.534 | Hard | 25,493 |
https://leetcode.com/problems/car-fleet-ii/discuss/2702324/Python3-or-Stack-Approach | class Solution:
def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:
n=len(cars)
ans=[-1]*n
stack=[]
for i in range(n-1,-1,-1):
while stack and cars[i][1]<=cars[stack[-1]][1]:
stack.pop()
while stack:
collisionTime=(cars[stack[-1]][0]-cars[i][0])/(cars[i][1]-cars[stack[-1]][1])
if collisionTime<=ans[stack[-1]] or ans[stack[-1]]==-1:
ans[i]=collisionTime
break
stack.pop()
stack.append(i)
return ans | car-fleet-ii | [Python3] | Stack Approach | swapnilsingh421 | 0 | 5 | car fleet ii | 1,776 | 0.534 | Hard | 25,494 |
https://leetcode.com/problems/car-fleet-ii/discuss/1087424/Python3-stack-O(N) | class Solution:
def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:
ans = [-1]*len(cars)
stack = []
for i, (x, v) in enumerate(reversed(cars)):
while stack and (v <= stack[-1][1] or (stack[-1][0] - x)/(v - stack[-1][1]) >= stack[-1][2]): stack.pop()
if stack:
t = (stack[-1][0] - x)/(v - stack[-1][1])
stack.append((x, v, t))
ans[~i] = t
else:
stack.append((x, v, inf))
return ans | car-fleet-ii | [Python3] stack O(N) | ye15 | 0 | 160 | car fleet ii | 1,776 | 0.534 | Hard | 25,495 |
https://leetcode.com/problems/car-fleet-ii/discuss/1086030/Python-Stack-of-Cars-O(n) | class Solution:
def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:
res = []
ahead = [(math.inf, 0)]
for pos, spd in reversed(cars):
while ahead and spd <= ahead[-1][1]:
ahead.pop()
atime = -1
while len(ahead) >= 2:
apos, aspd = ahead[-1]
npos, nspd = ahead[-2]
atime = (apos - pos)/(spd - aspd)
ntime = (npos - pos)/(spd - nspd)
if atime >= ntime:
ahead.pop()
else:
break
ahead.append((pos, spd))
res.append(atime)
res.reverse()
return res | car-fleet-ii | Python Stack of Cars O(n) | ajlai | 0 | 131 | car fleet ii | 1,776 | 0.534 | Hard | 25,496 |
https://leetcode.com/problems/car-fleet-ii/discuss/1085926/Python3-need-help-with-why-this-approach-is-wrong | class Solution:
def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:
times = [float(-1) for _ in range(len(cars))]
for i in range(1, len(cars)):
if cars[i-1][1] > cars[i][1]:
times[i-1] = self.timeToCollide(cars, i-1, i)
for i in range(len(cars)-3, -1, -1):
if times[i+1] == - 1.0: continue
# if car[i+1] collided before car[i], then we have to adjust times[i]
if times[i] > times[i+1]:
times[i] = self.correctTime(cars, times, i)
cars[i+1][1] = cars[i+2][1]
# if car[i+1] collided and speed became slower than cars[i], then we also have to adjust times[i]
elif cars[i][1] <= cars[i+1][1] and times[i+1] > 0.0:
if cars[i][1] > cars[i+2][1]:
times[i] = self.timeToCollide(cars, i, i+2)
return times
def timeToCollide(self, cars, i, j):
return (cars[j][0]-cars[i][0])/(cars[i][1] - cars[j][1])
def correctTime(self, cars, times, i):
return times[i+1] + (times[i]-times[i+1])*(cars[i][1] - cars[i+1][1])/(cars[i][1] - cars[i+2][1]) | car-fleet-ii | [Python3] need help with why this approach is wrong | hwsbjts | 0 | 69 | car fleet ii | 1,776 | 0.534 | Hard | 25,497 |
https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/discuss/1229047/Python-Easy-solution | class Solution:
def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
minDist = math.inf
ans = -1
for i in range(len(points)):
if points[i][0]==x or points[i][1]==y:
manDist = abs(points[i][0]-x)+abs(points[i][1]-y)
if manDist<minDist:
ans = i
minDist = manDist
return ans | find-nearest-point-that-has-the-same-x-or-y-coordinate | [Python] Easy solution | arkumari2000 | 20 | 2,300 | find nearest point that has the same x or y coordinate | 1,779 | 0.673 | Easy | 25,498 |
https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/discuss/2220848/Python3-simple-naive-approach | class Solution:
def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
result = None
maximumDistance = float("inf")
for index,point in enumerate(points):
a,b = point
distance = abs(x-a) + abs(y-b)
if distance < maximumDistance and (x == a or y == b):
maximumDistance = distance
result = index
return result if result != None else -1 | find-nearest-point-that-has-the-same-x-or-y-coordinate | π Python3 simple naive approach | Dark_wolf_jss | 5 | 302 | find nearest point that has the same x or y coordinate | 1,779 | 0.673 | Easy | 25,499 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.