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] <= 104This approach involves using dynamic programming with a sliding window to maintain the maximum sum at each position. For each position i in the array, calculate the maximum sum that can be achieved till that position, considering the constraint j - i <= k. Use a deque to track the indices which offer the maximum sum within the range of k.
The solution uses a dynamic programming array to store the maximum sum possible up to each index. It utilizes a deque to maintain useful indices that help in calculating the needed maximum sum over the moving window of size k without having to recompute every time.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of elements in the array nums. The space complexity is O(n) due to the storage of the dp array and deque.
By using a priority queue (or heap), we manage the maximum possible sum within the constraint more efficiently. We employ dynamic programming to calculate the possible maximal sum at each index while maintaining a priority queue to keep track of the relevant maximum sums.
C implementation utilizes a priority queue structure to keep maximum subsequences track. Through a heap-push and heap-pop approach, the subset with the highest value is computed dynamically across the moving windows.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log k) primarily due to heap operations. Space Complexity: O(n) is utilized by the dp array and the heap.
| Approach | Complexity |
|---|---|
| Dynamic Programming with Sliding Window Maximum | Time Complexity: O(n), where n is the number of elements in the array |
| Dynamic Programming with Priority Queue (Heap) | Time Complexity: O(n log k) primarily due to heap operations. Space Complexity: O(n) is utilized by the dp array and the heap. |
Leetcode 1498 - Number of Subsequences That Satisfy the Given Sum Condition - Python • NeetCode • 32,519 views views
Watch 9 more video solutions →Practice Constrained Subsequence Sum with our built-in code editor and test cases.
Practice on FleetCode