Maximum score possible from an array with jumps of at most length K
Given an array arr and an integer K, the 0th index, the task is to collect the maximum score possible by performing the following operations:
- Start from the 0th index of the array.
- Reach the last index of the array by jumping at most K indices in each move.
- Add the value of every index reached after each jump.
- Initialize an array dp to store the previously computed results.
- Now, starting from the 0th index, perform the following operations for every ith index:
- If the current index is greater than or equal to the index of the last element, return the last element of the array.
- If the value for the current index is pre-calculated, then return the pre-calculated value.
- Otherwise, calculate maximum score that can be obtained by moving to all steps in the range i + 1 to i + K and store results for respective indices in dp array using the following recurrence relation:
dp[i] = max(dp[i + 1], dp[i + 2], dp[i + 3], ….., dp[i + K]) + A[i].
- Now, print dp as the required answer.
Below is the implementation of the above approach:
Time Complexity: O(N * K)
Auxiliary Space: O(N * K)
Efficient Approach: Follow the steps below to solve the problem
- Initialize a Max Heap to store the result of previous K indices.
- Now, traverse the array A to calculate the maximum score for all indices.
- For 0th index, the score will be the value at the 0th index.
- Now, for every ith index in the range [1, N – 1].
- Firstly, remove maximum scores from the Max Heap for indices less than i – K.
- Now calculate the maximum score for ith index.
Maximum score = A[i] + score at the top of the Max Heap.
- Now insert the maximum score into the max heap with its index.
- Return the maximum score obtained.
Time Complexity: O(N * log K)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.