Related Articles

# Maximum score possible from an array with jumps of at most length K

• Last Updated : 03 May, 2021

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:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to count the maximum``// score of an index``int` `maxScore(``int` `i, ``int` `A[], ``int` `K, ``int` `N, ``int` `dp[])``{``    ``// Base Case``    ``if` `(i >= N - 1)``        ``return` `A[N - 1];` `    ``// If the value for the current``    ``// index is pre-calculated``    ``if` `(dp[i] != -1)``        ``return` `dp[i];` `    ``int` `score = INT_MIN;` `    ``// Calculate maximum score``    ``// for all the steps in the``    ``// range from i + 1 to i + k``    ``for` `(``int` `j = 1; j <= K; j++) {` `        ``// Score for index (i + j)``        ``score = max(score, maxScore(i + j, A, K, N, dp));``    ``}` `    ``// Update dp[i] and return``    ``// the maximum value``    ``return` `dp[i] = score + A[i];``}` `// Function to get maximum score``// possible from the array A[]``int` `getScore(``int` `A[], ``int` `N, ``int` `K)``{``    ``// Array to store memoization``    ``int` `dp[N];` `    ``// Initialize dp[] with -1``    ``for` `(``int` `i = 0; i < N; i++)``        ``dp[i] = -1;` `    ``cout << maxScore(0, A, K, N, dp);``}` `// Driver Code``int` `main()``{``    ``int` `A[] = { 100, -30, -50, -15, -20, -30 };``    ``int` `K = 3;``    ``int` `N = ``sizeof``(A) / ``sizeof``(A);` `    ``getScore(A, N, K);` `    ``return` `0;``}`

## Java

 `// JAVA program for the above approach``import` `java.io.*;``import` `java.math.*;``import` `java.util.*;``public` `class` `GFG``{` `  ``// Function to count the maximum``  ``// score of an index``  ``static` `int` `maxScore(``int` `i, ``int` `A[], ``int` `K, ``int` `N,``                      ``int` `dp[])``  ``{` `    ``// Base Case``    ``if` `(i >= N - ``1``)``      ``return` `A[N - ``1``];` `    ``// If the value for the current``    ``// index is pre-calculated``    ``if` `(dp[i] != -``1``)``      ``return` `dp[i];``    ``int` `score = Integer.MIN_VALUE;` `    ``// Calculate maximum score``    ``// for all the steps in the``    ``// range from i + 1 to i + k``    ``for` `(``int` `j = ``1``; j <= K; j++)``    ``{` `      ``// Score for index (i + j)``      ``score = Math.max(score,``                       ``maxScore(i + j, A, K, N, dp));``    ``}` `    ``// Update dp[i] and return``    ``// the maximum value``    ``return` `dp[i] = score + A[i];``  ``}` `  ``// Function to get maximum score``  ``// possible from the array A[]``  ``static` `void` `getScore(``int` `A[], ``int` `N, ``int` `K)``  ``{` `    ``// Array to store memoization``    ``int` `dp[] = ``new` `int``[N];` `    ``// Initialize dp[] with -1``    ``for` `(``int` `i = ``0``; i < N; i++)``      ``dp[i] = -``1``;``    ``System.out.println(maxScore(``0``, A, K, N, dp));``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main(String args[])``  ``{``    ``int` `A[] = { ``100``, -``30``, -``50``, -``15``, -``20``, -``30` `};``    ``int` `K = ``3``;``    ``int` `N = A.length;` `    ``getScore(A, N, K);``  ``}``}` `// This code is contributed by jyoti369`

## Python3

 `# Python program for the above approach``import` `sys` `# Function to count the maximum``# score of an index``def` `maxScore(i, A, K, N, dp):``  ` `    ``# Base Case``    ``if` `(i >``=` `N ``-` `1``):``        ``return` `A[N ``-` `1``];` `    ``# If the value for the current``    ``# index is pre-calculated``    ``if` `(dp[i] !``=` `-``1``):``        ``return` `dp[i];``    ``score ``=` `1``-``sys.maxsize;` `    ``# Calculate maximum score``    ``# for all the steps in the``    ``# range from i + 1 to i + k``    ``for` `j ``in` `range``(``1``, K ``+` `1``):``      ` `        ``# Score for index (i + j)``        ``score ``=` `max``(score, maxScore(i ``+` `j, A, K, N, dp));` `    ``# Update dp[i] and return``    ``# the maximum value``    ``dp[i] ``=` `score ``+` `A[i];``    ``return` `dp[i];`  `# Function to get maximum score``# possible from the array A``def` `getScore(A, N, K):``    ``# Array to store memoization``    ``dp ``=` `[``0``]``*``N;` `    ``# Initialize dp with -1``    ``for` `i ``in` `range``(N):``        ``dp[i] ``=` `-``1``;``    ``print``(maxScore(``0``, A, K, N, dp));` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``A ``=` `[``100``, ``-``30``, ``-``50``, ``-``15``, ``-``20``, ``-``30``];``    ``K ``=` `3``;``    ``N ``=` `len``(A);` `    ``getScore(A, N, K);``    ` `# This code contributed by shikhasingrajput`

## C#

 `// C# program for the above approach``using` `System;``class` `GFG``{` `  ``// Function to count the maximum``  ``// score of an index``  ``static` `int` `maxScore(``int` `i, ``int` `[]A, ``int` `K, ``int` `N,``                      ``int` `[]dp)``  ``{` `    ``// Base Case``    ``if` `(i >= N - 1)``      ``return` `A[N - 1];` `    ``// If the value for the current``    ``// index is pre-calculated``    ``if` `(dp[i] != -1)``      ``return` `dp[i];``    ``int` `score = ``int``.MinValue;` `    ``// Calculate maximum score``    ``// for all the steps in the``    ``// range from i + 1 to i + k``    ``for` `(``int` `j = 1; j <= K; j++)``    ``{` `      ``// Score for index (i + j)``      ``score = Math.Max(score,``                       ``maxScore(i + j, A, K, N, dp));``    ``}` `    ``// Update dp[i] and return``    ``// the maximum value``    ``return` `dp[i] = score + A[i];``  ``}` `  ``// Function to get maximum score``  ``// possible from the array A[]``  ``static` `void` `getScore(``int` `[]A, ``int` `N, ``int` `K)``  ``{` `    ``// Array to store memoization``    ``int` `[]dp = ``new` `int``[N];` `    ``// Initialize dp[] with -1``    ``for` `(``int` `i = 0; i < N; i++)``      ``dp[i] = -1;``    ``Console.WriteLine(maxScore(0, A, K, N, dp));``  ``}` `// Driver Code``static` `public` `void` `Main()``{``    ``int` `[]A = { 100, -30, -50, -15, -20, -30 };``    ``int` `K = 3;``    ``int` `N = A.Length;` `    ``getScore(A, N, K);``}``}` `// This code is contributed by jana_sayantan.`

## Javascript

 ``
Output
`55`

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.

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Structure to sort a priority queue on``// the basis of first element of the pair``struct` `mycomp {``    ``bool` `operator()(pair<``int``, ``int``> p1,``                    ``pair<``int``, ``int``> p2)``    ``{``        ``return` `p1.first < p2.first;``    ``}``};` `// Function to calculate maximum``// score possible from the array A[]``int` `maxScore(``int` `A[], ``int` `K, ``int` `N)``{``    ``// Stores the score of previous k indices``    ``priority_queue,``                ``vector >, mycomp>``        ``maxheap;` `    ``// Stores the maximum``    ``// score for current index``    ``int` `maxScore = 0;` `    ``// Maximum score at first index``    ``maxheap.push({ A, 0 });` `    ``// Traverse the array to calculate``    ``// maximum score for all indices``    ``for` `(``int` `i = 1; i < N; i++) {` `        ``// Remove maximum scores for``        ``// indices less than i - K``        ``while` `(maxheap.top().second < (i - K)) {``            ``maxheap.pop();``        ``}` `        ``// Calculate maximum score for current index``        ``maxScore = A[i] + maxheap.top().first;` `        ``// Push maximum score of``        ``// current index along``        ``// with index in maxheap``        ``maxheap.push({ maxScore, i });``    ``}` `    ``// Return the maximum score``    ``return` `maxScore;``}` `// Driver Code``int` `main()``{``    ``int` `A[] = { -44, -17, -54, 79 };``    ``int` `K = 2;``    ``int` `N = ``sizeof``(A) / ``sizeof``(A);` `    ``// Function call to calculate``    ``// maximum score from the array A[]``    ``cout << maxScore(A, K, N);` `    ``return` `0;``}`
Output
`18`

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.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up