Skip to content

Commit

Permalink
Time: 1363 ms (65.95%), Space: 30 MB (89.22%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
hovanhoa committed Oct 21, 2023
1 parent 9a79a3e commit 3c90356
Showing 1 changed file with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
# dp[i] := max sum of non-empty subsequence in nums[0..i]
dp = [0] * len(nums)
# dq stores dp[i - k], dp[i - k + 1], ..., dp[i - 1] whose values are > 0
# in decreasing order.
dq = collections.deque()

for i, num in enumerate(nums):
if dq:
dp[i] = max(dq[0], 0) + num
else:
dp[i] = num
while dq and dq[-1] < dp[i]:
dq.pop()
dq.append(dp[i])
if i >= k and dp[i - k] == dq[0]:
dq.popleft()

return max(dp)

0 comments on commit 3c90356

Please sign in to comment.