Dynamic Programming21 sections · 915 units
Open in Course

Constrained Sum - Walkthrough

Maximum sum with gap constraint

Find maximum sum of subsequence where adjacent elements are at most kk apart. dp[i]dp[i] = max sum ending at ii. Transition: dp[i]=nums[i]+max⁡(0,max⁡j∈[i−k,i−1]dp[j])dp[i] = nums[i] + \max(0, \max_{j \in [i-k, i-1]} dp[j]). The max⁡(0,...)\max(0, ...) handles starting fresh. Example: [10,2,−10,5,20][10, 2, -10, 5, 20], k=2k = 2. dp=[10,12,2,17,37]dp = [10, 12, 2, 17, 37]. At each step, query window max and add current.

Answer: max⁡(dp)=37\max(dp) = 37 (subsequence 10, 2, 5, 20). Monotonic queue handles the window max in O(1)O(1) amortized.