#1425

Constrained Subsequence Sum

Hard
ArrayDynamic ProgrammingQueueSliding WindowHeap (Priority Queue)Monotonic QueueDynamic ProgrammingSliding WindowDeque
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to build up the maximum sums while ensuring the k-distance condition is satisfied. We maintain a sliding window of maximum sums to efficiently calculate the best possible sum at each index.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a dp array where dp[i] represents the maximum sum of a subsequence ending at index i.
  2. 2Step 2: Use a deque to maintain the maximum dp values within the last k indices.
  3. 3Step 3: For each index i, calculate dp[i] as nums[i] + max(dp[j]) for j in the valid range, and update the deque accordingly.
  4. 4Step 4: The result will be the maximum value in the dp array.
solution.py17 lines
1# Full working Python code
2from collections import deque
3
4def maxSubsequenceSum(nums, k):
5    n = len(nums)
6    dp = [0] * n
7    max_sum = float('-inf')
8    dq = deque()
9    for i in range(n):
10        dp[i] = nums[i] + (dq[0] if dq else 0)
11        max_sum = max(max_sum, dp[i])
12        while dq and dq[-1] < dp[i]:
13            dq.pop()
14        dq.append(dp[i])
15        if i >= k:
16            dq.popleft()
17    return max_sum

Complexity note: The time complexity is linear because we process each element once, and the deque operations are amortized O(1). The space complexity is O(n) due to the dp array.

  • 1Dynamic programming can optimize problems involving subsequences.
  • 2Maintaining a sliding window of maximum values can significantly reduce time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.