Skip to content

Commit

Permalink
"Constrained Subsequence Sum" solution
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Oct 25, 2023
1 parent 357563b commit a8d030f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/constrained_subsequence_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import heapq


class Solution:
def constrainedSubsetSum(self, nums: list[int], k: int) -> int:
assert nums

result = nums[0]
heap = [(-nums[0], 0)]

for i in range(1, len(nums)):
while heap and i - heap[0][1] > k:
heapq.heappop(heap)

curr_max = max(nums[i], -heap[0][0] + nums[i])
result = max(result, curr_max)

heapq.heappush(heap, (-curr_max, i))

return result
15 changes: 15 additions & 0 deletions tests/test_constrained_subsequence_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import pytest

from src.constrained_subsequence_sum import Solution


@pytest.mark.parametrize(
"nums,k,expected",
(
([10, 2, -10, 5, 20], 2, 37),
([-1, -2, -3], 1, -1),
([10, -2, -10, -5, 20], 2, 23),
),
)
def test_solution(nums, k, expected):
assert Solution().constrainedSubsetSum(nums, k) == expected

0 comments on commit a8d030f

Please sign in to comment.