Open In App

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

Last Updated : 31 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] and an integer K, the 0th index, the task is to collect the maximum score possible by performing 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.
  • Examples :
  • Input: arr[] = {100, -30, -50, -15, -20, -30}, K = 3
    Output: 55
    Explanation: From 0th index, jump 3 indices ahead to arr[3] (= -15). From 3rd, jump 2 steps ahead to arr[5] (= -30). Therefore, the maximum score possible = (100 + (-15) + (-30)) = 55

    Input: arr[] = {-44, -17, -54, 79},  K = 2
    Output: 18

  • Naive Approach: The problem can be solved using recursion with memoization. Follow the steps below to solve the problem:
    • 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 index of 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:
        • 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].

        dp[i] = max(dp[i + 1], dp[i + 2], dp[i + 3], ….., dp[i + K]) + A[i]. 

      • Now, print dp[0] as the required answer.
  • Below is the implementation of the above approach:
  • C++




    // C++ program for the above approach
    #include <bits/stdc++.h>
    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[0]);
     
        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




    <script>
    // javascript program of the above approach
     
      // Function to count the maximum
      // score of an index
      function 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];
        let score = -1000;
     
        // Calculate maximum score
        // for all the steps in the
        // range from i + 1 to i + k
        for (let 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[]
      function getScore(A, N, K)
      {
     
        // Array to store memoization
        let dp = new Array(N).fill(-1);
     
        document.write(maxScore(0, A, K, N, dp));
      }
     
        // Driver Code
         
        let A = [ 100, -30, -50, -15, -20, -30 ];
        let K = 3;
        let N = A.length;
     
        getScore(A, N, K);
     
    </script>

    
    

  • Output

    55
    
    
    
    
    
  • Time Complexity: O(N * K)
    Auxiliary Space: O(N * K)
  • Maximum score possible from an array with jumps of at most length K using Dynamic Programming (Bottom up/Tabulation):

  • The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls.
  • Step-by-step approach:
    • Initialize a DP array of size N, where DP[i] represents the maximum score that can be obtained starting from position i.
    • Initialize DP[N-1] with the value of the last element of the array A.
    • Traverse the DP array from the second last index to the first.
    • For each index i, consider all possible steps that can be taken from that position, i.e., 1 to K steps forward.
    • For each step, calculate the maximum score that can be obtained by adding the score at the current position i to the maximum score that can be obtained from the destination position j.
    • Update DP[i] with the maximum score obtained among all the possible steps.
    • Return DP[0], which represents the maximum score that can be obtained starting from the first position.
  • Below is the implementation of the above approach:
  • C++




    // C++ program for above approach
     
    #include <bits/stdc++.h>
    using namespace std;
     
    int getScore(int A[], int N, int K) {
          // Initialize dp array with values for the last element
        int dp[N];
        dp[N - 1] = A[N - 1];
         
          // Traverse dp array from the second last index to the first
        for (int i = N - 2; i >= 0; i--) {
              // initial score
            int score = INT_MIN;
            for (int j = 1; j <= K && i + j < N; j++) {
                  // Update the score with the maximum value
                  // found among the possible steps
                score = max(score, dp[i + j]);
            }
              // Calculate the maximum score possible
            dp[i] = score + A[i];
        }
       
          // return answer
        return dp[0];
    }
     
    // Driver code
    int main() {
        int A[] = { 100, -30, -50, -15, -20, -30 };
        int K = 3;
        int N = sizeof(A) / sizeof(A[0]);
         
          //function call
        cout << getScore(A, N, K);
     
        return 0;
    }
     
    // this code is contributed by bhardwajji

    
    

    Java




    // Java program for above approach
    import java.util.Arrays;
     
    public class Main {
        public static int getScore(int[] A, int N, int K) {
            // Initialize dp array with values for the last element
            int[] dp = new int[N];
            dp[N - 1] = A[N - 1];
     
            // Traverse dp array from the second last index to the first
            for (int i = N - 2; i >= 0; i--) {
                // initial score
                int score = Integer.MIN_VALUE;
                for (int j = 1; j <= K && i + j < N; j++) {
                    // Update the score with the maximum value
                    // found among the possible steps
                    score = Math.max(score, dp[i + j]);
                }
                // Calculate the maximum score possible
                dp[i] = score + A[i];
            }
     
            // return answer
            return dp[0];
        }
         
          // Driver code
        public static void main(String[] args) {
            int[] A = { 100, -30, -50, -15, -20, -30 };
            int K = 3;
            int N = A.length;
     
            // function call
            System.out.println(getScore(A, N, K));
        }
    }

    
    

    Python3




    class Main:
        @staticmethod
        def getScore(A, N, K):
            # Initialize dp array with values for the last element
            dp = [0] * N
            dp[N - 1] = A[N - 1]
     
            # Traverse dp array from the second last index to the first
            for i in range(N - 2, -1, -1):
                # initial score
                score = float('-inf')
                for j in range(1, K + 1):
                    # Update the score with the maximum value
                    # found among the possible steps
                    if i + j < N:
                        score = max(score, dp[i + j])
                # Calculate the maximum score possible
                dp[i] = score + A[i]
     
            # return answer
            return dp[0]
     
    if __name__ == '__main__':
        A = [100, -30, -50, -15, -20, -30]
        K = 3
        N = len(A)
     
        # function call
        print(Main.getScore(A, N, K))

    
    

    C#




    using System;
     
    public class Program {
        public static int GetScore(int[] A, int N, int K) {
            // Initialize dp array with values for the last element
            int[] dp = new int[N];
            dp[N - 1] = A[N - 1];
     
            // Traverse dp array from the second last index to the first
            for (int i = N - 2; i >= 0; i--) {
                // initial score
                int score = int.MinValue;
                for (int j = 1; j <= K && i + j < N; j++) {
                    // Update the score with the maximum value
                    // found among the possible steps
                    score = Math.Max(score, dp[i + j]);
                }
                // Calculate the maximum score possible
                dp[i] = score + A[i];
            }
     
            // return answer
            return dp[0];
        }
         
        // Driver code
        public static void Main() {
            int[] A = { 100, -30, -50, -15, -20, -30 };
            int K = 3;
            int N = A.Length;
     
            // function call
            Console.WriteLine(GetScore(A, N, K));
        }
    }

    
    

    Javascript




    // JavaScript program for above approach
     
    function getScore(A, N, K) {
    // Initialize dp array with values for the last element
    let dp = new Array(N);
    dp[N - 1] = A[N - 1];
    // Traverse dp array from the second last index to the first
    for (let i = N - 2; i >= 0; i--) {
        // initial score
        let score = -Infinity;
        for (let j = 1; j <= K && i + j < N; j++) {
            // Update the score with the maximum value
            // found among the possible steps
            score = Math.max(score, dp[i + j]);
        }
        // Calculate the maximum score possible
        dp[i] = score + A[i];
    }
     
    // return answer
    return dp[0];
    }
     
    // Driver code
    let A = [100, -30, -50, -15, -20, -30];
    let K = 3;
    let N = A.length;
     
    // function call
    console.log(getScore(A, N, K));

    
    

  • Output

    55
    
    
    
    
    
  • Time Complexity: O(N * K), where N is the size of the array and K is the input variable
    Auxiliary Space: O(N)
  • Maximum score possible from an array with jumps of at most length K using Heap:

  • Step-by-step approach:
    • 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.
  • Below is the implementation of the above approach:
  • C++




    // C++ program for the above approach
    #include <bits/stdc++.h>
    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<pair<int, int>,
                    vector<pair<int, int> >, mycomp>
            maxheap;
     
        // Stores the maximum
        // score for current index
        int maxScore = 0;
     
        // Maximum score at first index
        maxheap.push({ A[0], 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[0]);
     
        // Function call to calculate
        // maximum score from the array A[]
        cout << maxScore(A, K, N);
     
        return 0;
    }

    
    

    Java




    // Java code for the above approach:
     
    import java.util.*;
     
    public class Main {
        static class IntPair {
            int first;
            int second;
            IntPair(int x, int y)
            {
                this.first = x;
                this.second = y;
            }
        }
        static class HeapComparator
            implements Comparator<IntPair> {
            public int compare(IntPair p1, IntPair p2)
            {
                if (p1.first < p2.first)
                    return 1;
                else if (p1.first > p2.first)
                    return -1;
                return 0;
            }
        }
        // Function to calculate maximum
        // score possible from the array A[]
        static int maxScore(int A[], int K, int N)
        {
            // Stores the score of previous k indices
            PriorityQueue<IntPair> maxheap
                = new PriorityQueue<IntPair>(
                    new HeapComparator());
     
            // Stores the maximum
            // score for current index
            int maxScore = 0;
     
            // Maximum score at first index
            maxheap.add(new IntPair(A[0], 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.peek().second < (i - K)) {
                    maxheap.remove();
                }
     
                // Calculate maximum score for current index
                maxScore = A[i] + maxheap.peek().first;
     
                // Push maximum score of
                // current index along
                // with index in maxheap
                maxheap.add(new IntPair(maxScore, i));
            }
     
            // Return the maximum score
            return maxScore;
        }
     
        // Driver Code
        public static void main(String args[])
        {
            int A[] = { -44, -17, -54, 79 };
            int K = 2;
            int N = A.length;
     
            // Function call to calculate
            // maximum score from the array A[]
            System.out.println(maxScore(A, K, N));
        }
    }
     
    // This code has been contributed by Sachin Sahara
    // (sachin801)

    
    

    Python3




    # Python program for the above approach
     
    # Function to calculate maximum
    # score possible from the array A[]
    def maxScore(A, K, N):
       
        # Stores the score of previous k indices
        maxheap = []
         
        # Stores the maximum
        # score for current index
        maxScore = 0
         
        # Maximum score at first index
        maxheap.append([A[0], 0])
         
        # Traverse the array to calculate
        # maximum score for all indices
        for i in range(1, N):
           
            # Remove maximum scores for
            # indices less than i - K
            while(maxheap[len(maxheap) - 1][1] < (i - K)):
                maxheap.pop()
                 
            # Calculate maximum score for current index
            maxScore = A[i] + maxheap[len(maxheap) - 1][0]
             
            # Push maximum score of
            # current index along
            # with index in maxheap
            maxheap.append([maxScore, i])
            maxheap.sort()
             
        # Return the maximum score
        return maxScore
     
    # Driver Code
    A = [-44, -17, -54, 79]
    K = 2
    N = len(A)
     
    # Function call to calculate
    # maximum score from the array A[]
    print(maxScore(A, K, N))
     
    # This code is contributed by Pushpesh Raj.

    
    

    C#




    // C# program for the above approach
     
    using System;
    using System.Collections.Generic;
     
    class GFG
     
    {
      // Function to calculate maximum
      // score possible from the array A[]
      static int maxScore(int[] A, int K, int N)
      {
        // Stores the score of previous k indices
        List<Tuple<int, int>> maxheap = new List<Tuple<int, int>> ();
     
        // Stores the maximum
        // score for current index
        int maxScore = 0;
     
        // Maximum score at first index
        maxheap.Add(Tuple.Create(A[0], 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[0].Item2 < (i - K)) {
            maxheap.RemoveAt(0);
          }
     
          // Calculate maximum score for current index
          maxScore = A[i] + maxheap[0].Item1;
     
          // Add maximum score of
          // current index along
          // with index in maxheap
          maxheap.Add(Tuple.Create(maxScore, i ));
          maxheap.Sort();
          maxheap.Reverse();
        }
     
        // Return the maximum score
        return maxScore;
      }
     
      // Driver Code
      public static void Main(string[] args)
      {
        int[] A = { -44, -17, -54, 79 };
        int K = 2;
        int N = A.Length;
     
        // Function call to calculate
        // maximum score from the array A[]
        Console.WriteLine(maxScore(A, K, N));
     
      }
    }
     
    // This code is contributed by phasing17.

    
    

    Javascript




    <script>
     
    // Javascript program for the above approach
     
    // Function to calculate maximum
    // score possible from the array A[]
    function maxScore(A, K, N)
    {
     
        // Stores the score of previous k indices
        var maxheap = [];
     
        // Stores the maximum
        // score for current index
        var maxScore = 0;
     
        // Maximum score at first index
        maxheap.push([A[0], 0]);
     
        // Traverse the array to calculate
        // maximum score for all indices
        for (var i = 1; i < N; i++) {
     
            // Remove maximum scores for
            // indices less than i - K
            while (maxheap[maxheap.length-1][1] < (i - K)) {
                maxheap.pop();
            }
     
            // Calculate maximum score for current index
            maxScore = A[i] + maxheap[maxheap.length-1][0];
     
            // Push maximum score of
            // current index along
            // with index in maxheap
            maxheap.push([maxScore, i]);
            maxheap.sort();
        }
     
        // Return the maximum score
        return maxScore;
    }
     
    // Driver Code
    var A = [-44, -17, -54, 79];
    var K = 2;
    var N = A.length;
     
    // Function call to calculate
    // maximum score from the array A[]
    document.write(maxScore(A, K, N));
     
    // This code is contributed by noob2000.
    </script>

    
    

  • Output

    18
    
    
    
    
    
  • Time Complexity: O(N * log K)
    Auxiliary Space: O(N)
  • Finding the maximum score using Deque:

  • In the previous approaches, we used a dp[] array such that dp[i] represents the maximum score that can be obtained starting from position i. And then we iterated over the last k positions to find the maximum among them. In order to find the maximum efficiently, we can simply maintain a Deque in sorted order to reduce the max previous score lookup from O(K) to O(1), reducing the overall time complexity to O(N).
  • Approach:
  • We maintain the deque such that we will pop (i-K-1)th index from queue since they are at a distance greater than K. Along with that, we will also pop those indices which will never have any chance of being chosen in the future. So for eg., if the score for current index – dp[i] is greater than some indices stored in the queue, it will always be optimal to choose dp[i] instead of those other indices. So, we will just pop those indices from queue since they won’t ever be used.

  • Step by step algorithm:
    • Create a deque maxQueue and add 0 to it.
    • Iterate from i = 1 to the size of array and for every element arr[i],
      • Check if the front element of maxQueue is less than i - k. If so, remove the front element.
      • Calculate the current result dp[i] as nums[i] + dp[maxQueue.front()].
      • Remove the back element from maxQueue, till dp[i] is greater than or equal to the value of dp[maxQueue.back()].
      • Add the current index i to the back of maxQueue.
    • Return the value of dp[n-1], which represents the maximum result.
  • Below is the implementation of the above approach:
  • C++




    #include <bits/stdc++.h>
    using namespace std;
     
    // Method to return the max score
    int getScore(vector<int>& arr, int N, int K)
    {
        // Max Queue to choose the maximum value of dp[] from
        // subarray dp[i-K...i-1]
        deque<int> maxQueue{ 0 };
        // dp array to store maximum score that can be obtained
        // starting from position
        vector<int> dp(N);
        dp[0] = arr[0];
        for (int i = 1; i < N; i++) {
            // Check if the element is at a distance greater
            // than K
            if (maxQueue.front() < i - K) {
                maxQueue.pop_front();
            }
            dp[i] = arr[i] + dp[maxQueue.front()];
            // Pop all those indices which will never have any
            // chance of being chosen in the future
            while (!maxQueue.empty()
                   && dp[i] >= dp[maxQueue.back()])
                maxQueue.pop_back();
            maxQueue.push_back(i);
        }
        // Return dp[n-1],¬†which is the maximum result
        return dp[N - 1];
    }
     
    int main()
    {
        // Sample Input
        vector<int> A{ 100, -30, -50, -15, -20, -30 };
        int K = 3;
        int N = A.size();
     
        // function call
        cout << (getScore(A, N, K));
        return 0;
    }

    
    

    Java




    import java.util.*;
     
    public class MaxScore {
        // Method to calculate the maximum score based on the rules
        public static int getScore(List<Integer> arr, int N, int K) {
            Deque<Integer> maxQueue = new LinkedList<>(); // Create a deque to store indices
            maxQueue.offer(0); // Initialize the deque with the first index
     
            int[] dp = new int[N]; // Create an array to store maximum scores
            dp[0] = arr.get(0); // Initialize the first score with the first element
     
            for (int i = 1; i < N; i++) {
                if (maxQueue.peekFirst() < i - K) {
                    maxQueue.pollFirst(); // Remove indices that are outside the window of K
                }
                dp[i] = arr.get(i) + dp[maxQueue.peekFirst()]; // Calculate the maximum score at index i
     
                // Remove indices from the back of the deque that have scores less than the current score
                while (!maxQueue.isEmpty() && dp[i] >= dp[maxQueue.peekLast()]) {
                    maxQueue.pollLast();
                }
                maxQueue.offer(i); // Add the current index to the deque
            }
     
            return dp[N - 1]; // Return the maximum score from the last index
        }
     
        public static void main(String[] args) {
            List<Integer> A = Arrays.asList(100, -30, -50, -15, -20, -30); // Sample input list
            int K = 3; // Window size
            int N = A.size(); // Size of the input list
     
            // Call the getScore method to find the maximum score
            System.out.println(getScore(A, N, K));
        }
    }

    
    

    Python3




    from collections import deque
     
    def get_score(arr, N, K):
        max_queue = deque()  # Create a deque to store indices
        max_queue.append(0# Initialize the deque with the first index
     
        dp = [0] * # Create a list to store maximum scores
        dp[0] = arr[0# Initialize the first score with the first element
     
        for i in range(1, N):
            while max_queue and max_queue[0] < i - K:
                max_queue.popleft()  # Remove indices that are outside the window of K
                 
            dp[i] = arr[i] + dp[max_queue[0]]  # Calculate the maximum score at index i
     
            while max_queue and dp[i] >= dp[max_queue[-1]]:
                max_queue.pop()  # Remove indices from the back of the deque with scores less than the current score
             
            max_queue.append(i)  # Add the current index to the deque
     
        return dp[N - 1# Return the maximum score from the last index
     
    def main():
        A = [100, -30, -50, -15, -20, -30# Sample input list
        K = 3  # Window size
        N = len(A)  # Size of the input list
     
        # Call the get_score function to find the maximum score
        print(get_score(A, N, K))
     
    if __name__ == "__main__":
        main()

    
    

    C#




    using System;
    using System.Collections.Generic;
     
    class MaxScore
    {
        // Method to calculate the maximum score based on the rules
        public static int GetScore(List<int> arr, int N, int K)
        {
            LinkedList<int> maxQueue = new LinkedList<int>(); // Create a deque to store indices
            maxQueue.AddLast(0); // Initialize the deque with the first index
     
            int[] dp = new int[N]; // Create an array to store maximum scores
            dp[0] = arr[0]; // Initialize the first score with the first element
     
            for (int i = 1; i < N; i++)
            {
                if (maxQueue.First.Value < i - K)
                {
                    maxQueue.RemoveFirst(); // Remove indices that are outside the window of K
                }
                dp[i] = arr[i] + dp[maxQueue.First.Value]; // Calculate the maximum score at index i
     
                // Remove indices from the back of the deque that have scores less than the current score
                while (maxQueue.Count > 0 && dp[i] >= dp[maxQueue.Last.Value])
                {
                    maxQueue.RemoveLast();
                }
                maxQueue.AddLast(i); // Add the current index to the deque
            }
     
            return dp[N - 1]; // Return the maximum score from the last index
        }
     
        public static void Main()
        {
            List<int> A = new List<int> { 100, -30, -50, -15, -20, -30 }; // Sample input list
            int K = 3; // Window size
            int N = A.Count; // Size of the input list
     
            // Call the GetScore method to find the maximum score
            Console.WriteLine(GetScore(A, N, K));
        }
    }

    
    

    Javascript




    function getScore(arr, N, K) {
        const maxQueue = []; // Array to store indices, acting as a deque
        maxQueue.push(0); // Initialize the deque with the first index
     
        const dp = new Array(N).fill(0); // Array to store maximum scores
        dp[0] = arr[0]; // Initialize the first score with the first element
     
        for (let i = 1; i < N; i++) {
            if (maxQueue[0] < i - K) {
                maxQueue.shift(); // Remove indices that are outside the window of K
            }
            dp[i] = arr[i] + dp[maxQueue[0]]; // Calculate the maximum score at index i
     
            // Remove indices from the back of the deque that have scores less than the current score
            while (maxQueue.length > 0 && dp[i] >= dp[maxQueue[maxQueue.length - 1]]) {
                maxQueue.pop();
            }
            maxQueue.push(i); // Add the current index to the deque
        }
     
        return dp[N - 1]; // Return the maximum score from the last index
    }
     
    // Sample input
    const A = [100, -30, -50, -15, -20, -30];
    const K = 3; // Window size
    const N = A.length; // Size of the input list
     
    // Call the getScore function to find the maximum score
    console.log(getScore(A, N, K));

    
    

  • Output

    55
    
    
    
    
    
  • Time Complexity: O(N), where N is the number of elements in the array arr[]
    Auxiliary Space: O(K), where K is the maximum length of jump.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads