Maximum score possible from an array with jumps of at most length K
Last Updated :
23 Jul, 2025
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));
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));
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));
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));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem