Open In App

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

Last Updated : 28 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] and an integer k. The task is to find the maximum score we can achieve by performing the following operations:

  • Start at the 0th index of the array.
  • Move to the last index of the array by jumping at most k indices at a time. For example, from the index i, we can jump to any index between i + 1 and i + k (inclusive) as long as it is within the bounds of the array.
  • Collect the value of each index we land on, including the value at the starting index (0th index).

Examples:

Input: arr[] = [100, -30, -50, -15, -20, -30], k = 3
Output: 55
Explanation: From 0th index, jump 3 indices ahead to arr[3]. From 3rd, jump 2 steps ahead to arr[5]. Therefore, the maximum score possible = (100 + (-15) + (-30)) = 55

Input: arr[] = [-44, -17, -54, 79],  k = 2
Output: 18
Explanation: From 0th index, jump 1 index ahead to arr[1]. From index 1, jump 2 steps ahead to arr[3]. Therefore, the maximum score possible = -44 + (-17) + 79 = 18.

Using Top-Down DP (Memoization) - O(n*k) Time and O(n) Space

The idea is to use recursion with memoization to explore all possible paths from the first index to the last, aiming to find the maximum score.

  • Starting from any index, the function calculates the score by adding the current index value and the score obtained from valid jumps within a range of k.
  • If the last index is reached, the value at that index is returned as the base case.
  • If a result for the current index has already been computed, it is retrieved from the memo[] array to avoid redundant calculations.

Steps to implement the above idea:

  • Initialize a memoization array with -1 to store computed results.
  • Define a recursive function that computes the maximum score from the current index, checking memoized values to avoid recomputation.
  • Base case: If at the last index, return its value.
  • Iterate through jumps (from 1 to k), recursively computing the score for each valid jump.
  • Memoize the maximum score obtained from all possible jumps at the current index.
C++
// C++ implamentation to find max score
// from at most k jumps using
// Recursion + Memoization
#include <bits/stdc++.h>
using namespace std;

// Function to calculate maximum score
int scoreHelper(vector<int> &arr, int k, 
                int index, vector<int> &memo) {

    // Return memoized value if already computed
    if (memo[index] != -1) {
        return memo[index];
    }

    // Return value at the last index if reached
    if (index == arr.size() - 1) {
        return arr[index];
    }

    // Initialize maxScore for current index
    int maxScore = INT_MIN;

    // Explore all valid jumps within range
    for (int jump = 1; jump <= k; jump++) {
        if (index + jump < arr.size()) {
            maxScore = max(maxScore, arr[index] + 
                       scoreHelper(arr, k, index + jump, memo));
        }
    }

    // Memoize the result for current index
    memo[index] = maxScore;
    return memo[index];
}

// Main function to get maximum score
int getScore(vector<int> &arr, int k) {

    // Memoization array
    vector<int> memo(arr.size(), -1);
    return scoreHelper(arr, k, 0, memo);
}

int main() {

    vector<int> arr = {100, -30, -50, -15, -20, -30};
    int k = 3;

    cout << getScore(arr, k) << endl;

    return 0;
}
Java
// Java implementation to find max score
// from at most k jumps using 
// Recursion + Memoization
import java.util.*;

class GfG {

    // Function to calculate maximum score
    static int scoreHelper(int[] arr, int k, 
                           int index, int[] memo) {
      
        // Return memoized value if already computed
        if (memo[index] != -1) {
            return memo[index];
        }

        // Return value at the last index if reached
        if (index == arr.length - 1) {
            return arr[index];
        }

        // Initialize maxScore for current index
        int maxScore = Integer.MIN_VALUE;

        // Explore all valid jumps within range
        for (int jump = 1; jump <= k; jump++) {
            if (index + jump < arr.length) {
                maxScore = Math.max(maxScore, 
                    arr[index] + scoreHelper(arr, k, 
                                             index + jump, memo));
            }
        }

        // Memoize the result for current index
        memo[index] = maxScore;
        return memo[index];
    }

    // Main function to get maximum score
    static int getScore(int[] arr, int k) {
      
        // Memoization array
        int[] memo = new int[arr.length];
        Arrays.fill(memo, -1);

        return scoreHelper(arr, k, 0, memo);
    }

    public static void main(String[] args) {

        int[] arr = {100, -30, -50, -15, -20, -30};
        int k = 3;

        System.out.println(getScore(arr, k));
    }
}
Python
# Python implementation to find max score 
# from at most k jumps using 
# Recursion + Memoization

# Function to calculate maximum score
def scoreHelper(arr, k, index, memo):

    # Return memoized value if already computed
    if memo[index] != -1:
        return memo[index]

    # Return value at the last index if reached
    if index == len(arr) - 1:
        return arr[index]

    # Initialize maxScore for current index
    maxScore = float('-inf')

    # Explore all valid jumps within range
    for jump in range(1, k + 1):
        if index + jump < len(arr):
            maxScore = max(
                maxScore, 
                arr[index] + scoreHelper(arr, k, index + jump, memo)
            )

    # Memoize the result for current index
    memo[index] = maxScore
    return memo[index]

# Main function to get maximum score
def getScore(arr, k):

    # Memoization array
    memo = [-1] * len(arr)
    return scoreHelper(arr, k, 0, memo)

if __name__ == "__main__":

    arr = [100, -30, -50, -15, -20, -30]
    k = 3

    print(getScore(arr, k))
C#
// C# implementation to find max score
// from at most k jumps using
// Recursion + Memoization
using System;

class GfG {

    // Function to calculate maximum score
    static int ScoreHelper(int[] arr, int k,
                                  int index, int[] memo) {

        // Return memoized value if already computed
        if (memo[index] != -1) {
            return memo[index];
        }

        // Return value at the last index if reached
        if (index == arr.Length - 1) {
            return arr[index];
        }

        // Initialize maxScore for current index
        int maxScore = int.MinValue;

        // Explore all valid jumps within range
        for (int jump = 1; jump <= k; jump++) {
            if (index + jump < arr.Length) {
                maxScore = Math.Max(
                    maxScore,
                    arr[index]
                        + ScoreHelper(arr, k, index + jump,
                                      memo));
            }
        }

        // Memoize the result for current index
        memo[index] = maxScore;
        return memo[index];
    }

    // Main function to get maximum score
    static int GetScore(int[] arr, int k) {

        // Memoization array
        int[] memo = new int[arr.Length];
        Array.Fill(memo, -1);

        return ScoreHelper(arr, k, 0, memo);
    }

    static void Main(string[] args) {
        int[] arr = { 100, -30, -50, -15, -20, -30 };
        int k = 3;

        Console.WriteLine(GetScore(arr, k));
    }
}
JavaScript
// JavaScript implementation to find max score
// from at most k jumps using
// Recursion + Memoization

// Function to calculate maximum score
function scoreHelper(arr, k, index, memo) {

    // Return memoized value if already computed
    if (memo[index] !== -1) {
        return memo[index];
    }

    // Return value at the last index if reached
    if (index === arr.length - 1) {
        return arr[index];
    }

    // Initialize maxScore for current index
    let maxScore = -Infinity;

    // Explore all valid jumps within range
    for (let jump = 1; jump <= k; jump++) {
        if (index + jump < arr.length) {
            maxScore = Math.max(
                maxScore,
                arr[index]
                    + scoreHelper(arr, k, index + jump,
                                  memo));
        }
    }

    // Memoize the result for current index
    memo[index] = maxScore;
    return memo[index];
}

// Main function to get maximum score
function getScore(arr, k) {

    // Memoization array
    let memo = new Array(arr.length).fill(-1);
    return scoreHelper(arr, k, 0, memo);
}

let arr = [ 100, -30, -50, -15, -20, -30 ];
let k = 3;
console.log(getScore(arr, k));

Output
55

Using Bottom-Up DP (Tabulation) - O(n*k) Time and O(n) Space

The idea is to use dynamic programming with a bottom-up approach to find the maximum score:

  • Instead of recursively exploring paths, a dp array stores the best possible score from each index to the end.
  • The solution builds backward, ensuring each index considers the best jump within k steps using previously computed results.
  • This avoids redundant calculations, making it more efficient than recursion. The final answer is found at dp[0], representing the maximum score from the start.

Steps to implement the above idea:

  • Initialize a dp array of size n with minimum integer value.
  • Set the last index of dp as arr[n-1] (base case).
  • Iterate backward from the second last index to the first.
  • For each index, check all valid jumps up to k steps.
  • Update dp[i] as the maximum possible score from that index.
  • Return dp[0], which gives the maximum score from the start.
C++
// C++ implementation to find max score
// from at most k jumps using Tabulation
#include <bits/stdc++.h>
using namespace std;

// Function to calculate maximum score using Tabulation
int getScore(vector<int> &arr, int k) {

    int n = arr.size();

    // Tabulation array to store maximum scores
    vector<int> dp(n, INT_MIN);

    // Base case: score at the last index is the
    // value at that index
    dp[n - 1] = arr[n - 1];

    // Iterate from second last index to the first
    for (int i = n - 2; i >= 0; i--) {

        // Calculate max score by considering all valid jumps
        for (int jump = 1; jump <= k; jump++) {
            if (i + jump < n) {
                dp[i] = max(dp[i], arr[i] + dp[i + jump]);
            }
        }
    }

    // Return the maximum score starting
    // from the first index
    return dp[0];
}

int main() {

    vector<int> arr = {100, -30, -50, -15, -20, -30};
    int k = 3;

    cout << getScore(arr, k) << endl;

    return 0;
}
Java
// Java implementation to find max score
// from at most k jumps using Tabulation
import java.util.*;

class GfG {

    // Main function to get maximum score
    static int getScore(int[] arr, int k) {

        int n = arr.length;

        // Tabulation array to store scores
        int[] dp = new int[n];

        // Base case: score at the last index
        dp[n - 1] = arr[n - 1];

        // Iterate from second last index to first
        for (int i = n - 2; i >= 0; i--) {

            // Initialize maxScore for current index
            dp[i] = Integer.MIN_VALUE;

            // Calculate max score for valid jumps
            for (int jump = 1; jump <= k; jump++) {
                if (i + jump < n) {
                    dp[i] = Math.max(dp[i],
                                     arr[i] + dp[i + jump]);
                }
            }
        }

        // Return score from the first index
        return dp[0];
    }

    public static void main(String[] args) {

        int[] arr = { 100, -30, -50, -15, -20, -30 };
        int k = 3;

        System.out.println(getScore(arr, k));
    }
}
Python
# Python implementation to find max score 
# from at most k jumps using Tabulation

# Main function to get maximum score
def getScore(arr, k):

    n = len(arr)

    # Tabulation array to store scores
    dp = [float('-inf')] * n

    # Base case: score at the last index
    dp[n - 1] = arr[n - 1]

    # Iterate from second last index to first
    for i in range(n - 2, -1, -1):

        # Calculate max score for all valid jumps
        for jump in range(1, k + 1):
            if i + jump < n:
                dp[i] = max(dp[i], 
                            arr[i] + dp[i + jump])

    # Return score from the first index
    return dp[0]

if __name__ == "__main__":

    arr = [100, -30, -50, -15, -20, -30]
    k = 3

    print(getScore(arr, k))
C#
// C# implementation to find max score
// from at most k jumps using Tabulation
using System;

class GfG {

    // Main function to get maximum score
    static int GetScore(int[] arr, int k) {

        int n = arr.Length;

        // Tabulation array to store scores
        int[] dp = new int[n];
        Array.Fill(dp, int.MinValue);

        // Base case: score at the last index
        dp[n - 1] = arr[n - 1];

        // Iterate from second last index to first
        for (int i = n - 2; i >= 0; i--) {

            // Calculate max score for all valid jumps
            for (int jump = 1; jump <= k; jump++) {
                if (i + jump < n) {
                    dp[i] = Math.Max(dp[i],
                                     arr[i] + dp[i + jump]);
                }
            }
        }

        // Return score from the first index
        return dp[0];
    }

    static void Main(string[] args) {

        int[] arr = { 100, -30, -50, -15, -20, -30 };
        int k = 3;

        Console.WriteLine(GetScore(arr, k));
    }
}
JavaScript
// JavaScript implementation to find max score
// from at most k jumps using Tabulation

// Main function to get maximum score
function getScore(arr, k) {

    let n = arr.length;

    // Tabulation array to store scores
    let dp = new Array(n).fill(-Infinity);

    // Base case: score at the last index
    dp[n - 1] = arr[n - 1];

    // Iterate from second last index to first
    for (let i = n - 2; i >= 0; i--) {

        // Calculate max score for all valid jumps
        for (let jump = 1; jump <= k; jump++) {
            if (i + jump < n) {
                dp[i] = Math.max(dp[i],
                                 arr[i] + dp[i + jump]);
            }
        }
    }

    // Return score from the first index
    return dp[0];
}

let arr = [ 100, -30, -50, -15, -20, -30 ];
let k = 3;

console.log(getScore(arr, k));

Output
55

Using DP + Heap - O(n*log(k)) Time and O(k) Space

The idea is to improve the efficiency of the basic tabulation method by using a max-heap.

  • In the simple tabulation method, for each index, all possible jumps within the range k are evaluated, which can be time-consuming when k is large.
  • To optimize this, the max-heap dynamically tracks the maximum scores within the valid range, ensuring faster access to the best possible jump.
  • The heap allows the algorithm to focus only on the relevant scores, making the computation significantly faster.

Steps to implement the above idea:

  • Initialize a dp array of size n with minimum integer value.
  • Set dp[n-1] as arr[n-1] and push it into a max-heap.
  • Iterate backward from the second last index to the first.
  • Remove out-of-range elements from the heap (index > i + k).
  • Set dp[i] as the max heap's top value + arr[i].
  • Push dp[i] and its index into the max-heap and return dp[0].
C++
// C++ implementation to find max score
// from at most k jumps using Tabulation + Heap
#include <bits/stdc++.h>
using namespace std;

int getScore(vector<int> &arr, int k) {
    int n = arr.size();

    vector<int> dp(n, INT_MIN);

    // Base case: score at the last index is the
    // value at that index
    dp[n - 1] = arr[n - 1];

    // Max-heap to store {dp[index], index}
    priority_queue<pair<int, int>> maxh;
    maxh.push({dp[n - 1], n - 1});

    // Iterate from second last index to the first
    for (int i = n - 2; i >= 0; i--) {

        // Remove out-of-range elements from the heap
        while (maxh.size() && maxh.top().second > i + k) {
            maxh.pop();
        }

        // Set dp[i] as the max value from the valid
        // range + current index value
        dp[i] = maxh.top().first + arr[i];

        // Push current dp[i] and index into the heap
        maxh.push({dp[i], i});
    }

    // Return the maximum score starting from the
    // first index
    return dp[0];
}

int main() {

    vector<int> arr = {100, -30, -50, -15, -20, -30};
    int k = 3;

    cout << getScore(arr, k) << endl;

    return 0;
}
Java
// Java implementation to find max score
// from at most k jumps using Tabulation + Heap
import java.util.*;

class GfG {

    static int getScore(int[] arr, int k) {

        int n = arr.length;

        // Tabulation array to store scores
        int[] dp = new int[n];

        // Base case: score at the last index
        dp[n - 1] = arr[n - 1];

        // Max-heap to store {dp[index], index}
        PriorityQueue<int[]> maxh = new PriorityQueue<>(
            (a, b) -> Integer.compare(b[0], a[0]));
        maxh.offer(new int[] { dp[n - 1], n - 1 });

        // Iterate from second last index to first
        for (int i = n - 2; i >= 0; i--) {

            // Remove out-of-range elements from the heap
            while (!maxh.isEmpty()
                   && maxh.peek()[1] > i + k) {
                maxh.poll();
            }

            // Set dp[i] as the max value from the valid
            // range
            // + current index value
            dp[i] = maxh.peek()[0] + arr[i];

            // Push current dp[i] and index into the heap
            maxh.offer(new int[] { dp[i], i });
        }

        // Return score from the first index
        return dp[0];
    }

    public static void main(String[] args) {

        int[] arr = { 100, -30, -50, -15, -20, -30 };
        int k = 3;

        System.out.println(getScore(arr, k));
    }
}
Python
# Python implementation to find max score 
# from at most k jumps using Tabulation + Heap
import heapq

def getScore(arr, k):
    n = len(arr)
    
    # Tabulation array to store maximum scores
    dp = [float('-inf')] * n
    
    # Base case: score at the last index is the
    # value at that index
    dp[n - 1] = arr[n - 1]
    
    # Max-heap to store {dp[index], index}
    maxh = []
    heapq.heappush(maxh, (-dp[n - 1], n - 1))  

    # Iterate from second last index to the first
    for i in range(n - 2, -1, -1):
        
        # Remove out-of-range elements from the heap
        while maxh and maxh[0][1] > i + k:
            heapq.heappop(maxh)
        
        # Set dp[i] as the max value from the valid 
        # range + current index value
        dp[i] = -maxh[0][0] + arr[i]
        
        # Push current dp[i] and index into the heap
        heapq.heappush(maxh, (-dp[i], i))

    # Return the maximum score starting from the 
    # first index
    return dp[0]

if __name__ == "__main__":

    arr = [100, -30, -50, -15, -20, -30]
    k = 3

    print(getScore(arr, k))
C#
// C# implementation to find max score
// from at most k jumps using Tabulation + Heap
using System;
using System.Collections.Generic;

class GfG {

    static int GetScore(int[] arr, int k) {
       
        int n = arr.Length;
        
        // Tabulation array to store scores
        int[] dp = new int[n];
        
        // Base case: score at the last index
        dp[n - 1] = arr[n - 1];
        
        // Max Heap to store indices of dp values 
        // in decreasing order
        LinkedList<int> maxh = new LinkedList<int>();
        maxh.AddLast(n - 1);
        
        // Iterate from second last index to the first
        for (int i = n - 2; i >= 0; i--) {
            // Remove indices from the heap that are out of range
            while (maxh.Count > 0 && maxh.First.Value > i + k) {
                maxh.RemoveFirst();
            }
            
            // Set dp[i] as the maximum score from the heap
            dp[i] = arr[i] + dp[maxh.First.Value];
            
            // Maintain the heap in decreasing order of dp values
            while (maxh.Count > 0 && dp[i] >= dp[maxh.Last.Value]) {
                maxh.RemoveLast();
            }
            
            // Add the current index to the heap
            maxh.AddLast(i);
        }
        
        // Return the maximum score starting 
        // from the first index
        return dp[0]; 
      
    }

    static void Main(string[] args) {
        int[] arr = { 100, -30, -50, -15, -20, -30 };
        int k = 3;

        Console.WriteLine(GetScore(arr, k));
    }
}
JavaScript
// JavaScript implementation to find max score 
// from at most k jumps using Tabulation + Heap

function getScore(arr, k) {
    let n = arr.length;

    // Tabulation array to store maximum scores
    let dp = new Array(n).fill(Number.NEGATIVE_INFINITY);

    // Base case: score at the last index is the
    // value at that index
    dp[n - 1] = arr[n - 1];

    // Max-heap to store {dp[index], index}
    let maxh = [];
    maxh.push([dp[n - 1], n - 1]);

    // Iterate from second last index to the first
    for (let i = n - 2; i >= 0; i--) {

        // Remove out-of-range elements from the heap
        while (maxh.length && maxh[0][1] > i + k) {
            maxh.shift();
        }

        // Set dp[i] as the max value from the valid 
        // range + current index value
        dp[i] = maxh[0][0] + arr[i];

        // Push current dp[i] and index into the heap
        maxh.push([dp[i], i]);

        // Sort heap to maintain max-heap property
        maxh.sort((a, b) => b[0] - a[0]);
    }

    // Return the maximum score starting from the 
    // first index
    return dp[0];
}

let arr = [100, -30, -50, -15, -20, -30];
let k = 3;

console.log(getScore(arr, k));

Output
55

Using DP + Deque - O(n) Time and O(k) Space

The Deque (Double-Ended Queue) provides an efficient alternative to the max-heap by maintaining a sliding window of indices corresponding to maximum values in the dp array. Unlike a heap, which requires logarithmic operations, the deque allows for constant time operations to remove outdated indices and insert new ones, making it ideal for this problem.

Steps to implement the above idea:

  • Initialize a dp array of size n with minimum integer value.
  • Set dp[n-1] as arr[n-1] and push its index into a deque.
  • Iterate backward from the second last index to the first.
  • Remove out-of-range indices from the front of the deque.
  • Set dp[i] as arr[i] + dp[dq.front()].
  • Maintain deque order, remove smaller values from the back, and push I.
C++
// C++ implementation to find max score
// from at most k jumps using Tabulation + Deque
#include <bits/stdc++.h>
using namespace std;

// Function to calculate maximum score using
// Tabulation + Deque
int getScore(vector<int> &arr, int k) {
    int n = arr.size();

    // Tabulation array to store maximum scores
    vector<int> dp(n, INT_MIN);

    // Base case: score at the last index is the
    // value at that index
    dp[n - 1] = arr[n - 1];

    // Deque to store indices of dp values in
    // decreasing order
    deque<int> dq;
    dq.push_back(n - 1);

    // Iterate from second last index to the first
    for (int i = n - 2; i >= 0; i--) {

        // Remove indices from the deque that are out of range
        while (!dq.empty() && dq.front() > i + k) {
            dq.pop_front();
        }

        // Set dp[i] as the maximum score from the deque
        dp[i] = arr[i] + dp[dq.front()];

        // Maintain the deque in decreasing order of dp values
        while (!dq.empty() && dp[i] >= dp[dq.back()]) {
            dq.pop_back();
        }

        // Add the current index to the deque
        dq.push_back(i);
    }

    // Return the maximum score starting from the
    // first index
    return dp[0];
}

int main() {

    vector<int> arr = {100, -30, -50, -15, -20, -30};
    int k = 3;

    cout << getScore(arr, k) << endl;

    return 0;
}
Java
// Java implementation to find max score
// from at most k jumps using Tabulation + Deque
import java.util.*;

class GfG {

    static int getScore(int[] arr, int k) {

        int n = arr.length;

        // Tabulation array to store scores
        int[] dp = new int[n];

        // Base case: score at the last index
        dp[n - 1] = arr[n - 1];

        // Deque to store indices of dp values 
        // in decreasing order
        Deque<Integer> dq = new LinkedList<>();
        dq.offer(n - 1);  

        // Iterate from second last index to the first
        for (int i = n - 2; i >= 0; i--) {

            // Remove indices from the deque that are out of range
            while (!dq.isEmpty() && dq.peekFirst() > i + k) {
                dq.pollFirst();
            }

            // Set dp[i] as the maximum score from the deque
            dp[i] = arr[i] + dp[dq.peekFirst()];

            // Maintain the deque in decreasing order of dp values
            while (!dq.isEmpty() && dp[i] >= dp[dq.peekLast()]) {
                dq.pollLast();
            }

            // Add the current index to the deque
            dq.offerLast(i);
        }

        // Return the maximum score starting 
        // from the first index
        return dp[0];
    }

    public static void main(String[] args) {

        int[] arr = {100, -30, -50, -15, -20, -30};
        int k = 3;

        System.out.println(getScore(arr, k));
    }
}
Python
# Python implementation to find max score 
# from at most k jumps using Tabulation + Deque

# Main function to get maximum score
from collections import deque

def getScore(arr, k):

    n = len(arr)

    # Tabulation array to store scores
    dp = [float('-inf')] * n

    # Base case: score at the last index
    dp[n - 1] = arr[n - 1]

    # Deque to store indices of dp values 
    # in decreasing order
    dq = deque([n - 1])

    # Iterate from second last index to first
    for i in range(n - 2, -1, -1):

        # Remove indices from deque that are out of range
        while dq and dq[0] > i + k:
            dq.popleft()

        # Set dp[i] as the maximum score from the deque
        dp[i] = arr[i] + dp[dq[0]]

        # Maintain deque in decreasing order of dp values
        while dq and dp[i] >= dp[dq[-1]]:
            dq.pop()

        # Add current index to the deque
        dq.append(i)

    # Return score from the first index
    return dp[0]

if __name__ == "__main__":

    arr = [100, -30, -50, -15, -20, -30]
    k = 3

    print(getScore(arr, k))
C#
// C# implementation to find max score 
// from at most k jumps using Tabulation + Deque
using System;
using System.Collections.Generic;

class GfG {

    static int GetScore(int[] arr, int k) {

        int n = arr.Length;
        
        // Tabulation array to store scores
        int[] dp = new int[n];
        
        // Base case: score at the last index
        dp[n - 1] = arr[n - 1];
        
        // Deque to store indices of dp values 
        // in decreasing order
        LinkedList<int> dq = new LinkedList<int>();
        dq.AddLast(n - 1);
        
        // Iterate from second last index to the first
        for (int i = n - 2; i >= 0; i--) {
            // Remove indices from the deque that are out of range
            while (dq.Count > 0 && dq.First.Value > i + k) {
                dq.RemoveFirst();
            }
            
            // Set dp[i] as the maximum score from the deque
            dp[i] = arr[i] + dp[dq.First.Value];
            
            // Maintain the deque in decreasing order of dp values
            while (dq.Count > 0 && dp[i] >= dp[dq.Last.Value]) {
                dq.RemoveLast();
            }
            
            // Add the current index to the deque
            dq.AddLast(i);
        }
        
        // Return the maximum score starting 
        // from the first index
        return dp[0];
    }

    static void Main(string[] args) {

        int[] arr = {100, -30, -50, -15, -20, -30};
        int k = 3;

        Console.WriteLine(GetScore(arr, k));
    }
}
JavaScript
// JavaScript implementation to find max score 
// from at most k jumps using Tabulation + Deque

function getScore(arr, k) {

    let n = arr.length;

    // Tabulation array to store scores
    let dp = new Array(n).fill(-Infinity);

    // Base case: score at the last index
    dp[n - 1] = arr[n - 1];

    // Deque to store indices of dp values
    // in decreasing order
    let dq = [];

    // Add the last index to the deque
    dq.push(n - 1);

    // Iterate from second last index to first
    for (let i = n - 2; i >= 0; i--) {

        // Remove indices from deque that are out of range
        while (dq.length > 0 && dq[0] > i + k) {
            dq.shift();
        }

        // Set dp[i] as the maximum score from the deque
        dp[i] = arr[i] + dp[dq[0]];

        // Maintain deque in decreasing order of dp values
        while (dq.length > 0 && dp[i] >= dp[dq[dq.length - 1]]) {
            dq.pop();
        }

        // Add current index to the deque
        dq.push(i);
    }

    // Return score from the first index
    return dp[0];
}

//Driver code
let arr = [100, -30, -50, -15, -20, -30];
let k = 3;

console.log(getScore(arr, k));

Output
55

Next Article

Similar Reads