![]() |
VOOZH | about |
Given an array arr[] of size n, and an integer k. The task is to find the maximum sum of a subsequence that satisfies the following two conditions:
Examples:
Input: arr[] = [10, -5, -2, 4, 0, 3], k = 3
Output: 17
Explanation: Start at arr[0] = 10 → jump to arr[3] = 4 → jump to arr[5] = 3. Total sum = 10 + 4 + 3 = 17.Input: arr[] = [1, -5, -20, 4, -1, 3, -6, -3], k = 2
Output: 0
Explanation: Best path starting from arr[0] = 1 to arr[7] = -3 using max jump k = 2 gives maximum possible sum = 0.Input: arr[] = [-1, -2, -3, -4], k = 1
Output: -10
Table of Content
The idea is to explore all possible valid subsequences starting from arr[0] and ending at arr[n - 1], where each selected element's index is within k steps from the previous one. The thought process is to use recursion to try every path, accumulate the sum, and update the maximum sum found.
- At each recursive call, we try jumping to every index from idx + 1 to idx + k if it’s within bounds.
- The base case is when we reach the last index, at which point we check if the current sum is higher than the current maximum.
- Backtracking helps undo the current choice and try alternate paths, ensuring complete exploration of possibilities.
17
The idea is to use Dynamic Programming with a Deque to efficiently maintain the maximum sum reachable at each index. The thought process is: for every index i, we want the maximum dp[j] (where i-k ≤ j < i) to add arr[i] to it. We use a Deque to store potential j indices in a way that always keeps the maximum at the front, allowing O(1) access. The key observation is that we can discard smaller dp values from the back of the deque since they’ll never contribute to a better solution.
Steps-By-Step Implementation
17