# Solving Leetcode Interviews in Seconds with AI: Constrained Subsequence Sum


	# Introduction
	In this blog post, we will explore how to solve the LeetCode problem "1425" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like [Chatmagic](https://www.chatmagic.app), we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

	# Problem Statement
	> Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied. A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.   Example 1:  Input: nums = [10,2,-10,5,20], k = 2 Output: 37 Explanation: The subsequence is [10, 2, 5, 20].  Example 2:  Input: nums = [-1,-2,-3], k = 1 Output: -1 Explanation: The subsequence must be non-empty, so we choose the largest number.  Example 3:  Input: nums = [10,-2,-10,-5,20], k = 2 Output: 23 Explanation: The subsequence is [10, -2, -5, 20].    Constraints:  1 <= k <= nums.length <= 105 -104 <= nums[i] <= 104  

	# Explanation
	Here's the breakdown of the solution:

*   **Dynamic Programming with a Deque:** The problem can be solved using dynamic programming. `dp[i]` stores the maximum sum of a subsequence ending at index `i`. We use a deque to efficiently maintain a sliding window of the best `dp` values within the allowed range `k`.
*   **Deque for Optimization:** The deque stores indices of potentially optimal `dp` values. It ensures that the deque only contains indices `j` such that `dp[j]` is greater than or equal to `dp[x]` for all `x` in the deque where `j < x`. This allows us to quickly find the best preceding element to extend the subsequence.
*   **Handling All Negative Numbers:** If all numbers are negative, the subsequence must consist of only the largest negative number.

*   **Runtime Complexity:** O(N)
*   **Storage Complexity:** O(N)

	
	# Code
	```python
	from collections import deque

def constrainedSubsetSum(nums, k):
    n = len(nums)
    dp = [0] * n
    dp[0] = nums[0]
    deque_obj = deque([0])
    max_sum = nums[0]

    for i in range(1, n):
        while deque_obj and deque_obj[0] < i - k:
            deque_obj.popleft()

        if deque_obj:
            dp[i] = max(nums[i], nums[i] + dp[deque_obj[0]])
        else:
            dp[i] = nums[i]

        max_sum = max(max_sum, dp[i])

        while deque_obj and dp[deque_obj[-1]] <= dp[i]:
            deque_obj.pop()

        deque_obj.append(i)

    return max_sum
	```
			
