Data Structures19 sections · 729 units
Open in Course

Problem - Constrained Subsequence Sum

DP with deque

Given an integer array numsnums and an integer kk, return the maximum sum of a non-empty subsequence such that for every two consecutive integers in the subsequence, nums[i]nums[i] and nums[j]nums[j], where i<ji < j, the condition jikj - i \leq k is satisfied.

You're solving a dynamic programming problem where the transition looks at the last kk states. A naive DP is O(nk)O(nk). With a monotonic deque, it's O(n)O(n).