Maximize count of elements reaching the end of an Array
Last Updated :
15 Jul, 2025
Given an array arr[] consisting of N integers, where each element denotes the maximum number of elements that can be placed on that index and an integer X, which denotes the maximum indices that can be jumped from an index, the task is to find the number of elements that can reach the end of the array.
Note: After placing an element in the ith index, arr[i] decreases by 1. Therefore, maximum number of elements that can be placed in the ith index is arr[i].
Examples:
Input: arr[] = {1, 0, 2, 1, 0, 4}, X = 3
Output: 3
Explanation:
Since X = 3, elements can be placed initially in arr[0], arr[1] and arr[2]
One element can be placed in arr[0] which can make jumps to arr[3] followed by arr[5] to reach the end of the array.
Now, the modified array is {0, 0, 2, 0, 0, 3}
Place two elements in arr[2] which jumps to arr[5] to reach the end of the array.
Since the array modifies to {0, 0, 0, 0, 0, 1}, no more elements can reach the end of the array as arr[0] = arr[1] = arr[2] = 0.
Therefore, a maximum of 3 elements can reach the end of the array
Input: arr[] = {1, 0, 0, 2}, X = 3
Output: 1
Binary Search Approach:
Follow the below steps to solve the problem:
- Initialize low = 1 and high = sum of all the array elements.
- Compute mid between low and high
- If mid is less than minimum of all the X length windows, then update low = mid + 1.
- Otherwise, update high = mid - 1.
- Repeat the above steps until low exceeds high. Finally, print low - 1 as the answer.
Below is implementation of the above approach:
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
#define LL long long
// Function to check if mid elements
// can reach the end of the array or not
bool possible(vector<LL>& a, vector<LL>& pre,
LL mid, int jump)
{
// Size of the vector
int n = a.size();
// Sum of the first window of length jump
LL ans = pre[min(n - 1, jump - 1)];
for (int i = jump; i < n; ++i) {
// Extract the minimum sum of
// length jump from all windows
// of the array
if (i >= jump) {
ans
= min(ans, pre[i] - pre[i - jump]);
}
else
ans = pre[i];
}
if (ans >= mid)
return true;
else
return false;
}
// Function to count the maximum
// number of elements that can reach the
// end of the array
LL findMax(vector<LL>& a, int jumpLen)
{
// Size of the array
int n = a.size();
// Stores the prefix sums
vector<LL> pre(n);
// Compute the prefix array
// from the given array
pre[0] = a[0];
for (int i = 1; i < (int)a.size(); ++i) {
pre[i] = pre[i - 1] + a[i];
}
// Initialising low and high
LL low = 1, high = pre[n - 1];
// Perform binary search
while (low <= high) {
// Calculate mid
LL mid = (low + high) / 2;
// Check if mid no of elements
// can reach the end or not
if (possible(a, pre, mid, jumpLen)) {
// Update low to check if higher
// number of elements can reach
// the end of the array
low = mid + 1;
}
// Otherwise
else {
// Update high
high = mid - 1;
}
}
// Return the maximum
return low - 1;
}
// Driver Code
int main()
{
int x = 2;
vector<LL> a = { 1, 1, 1, 1, 1, 1 };
cout << findMax(a, x) << endl;
}
Java
import java.util.*;
// Java Program to implement
// the above approach
class GFG{
// Function to check if mid elements
// can reach the end of the array or not
static boolean possible(int[] a, int[] pre,
int mid, int jump)
{
// Size of the vector
int n = a.length;
// Sum of the first window of length jump
int ans = pre[(Math.min(n - 1, jump - 1))];
for (int i = jump; i < n; ++i)
{
// Extract the minimum sum of
// length jump from all windows
// of the array
if (i >= jump)
{
ans = Math.min(ans, pre[i] -
pre[i - jump]);
}
else
ans = pre[i];
}
if (ans >= mid)
return true;
else
return false;
}
// Function to count the maximum
// number of elements that can reach the
// end of the array
static int findMax(int []a, int jumpLen)
{
// Size of the array
int n = a.length;
// Stores the prefix sums
int []pre = new int[n];
// Compute the prefix array
// from the given array
pre[0] = a[0];
for (int i = 1; i < n; ++i)
{
pre[i] = pre[i - 1] + a[i];
}
// Initialising low and high
int low = 1, high = pre[n - 1];
// Perform binary search
while (low <= high)
{
// Calculate mid
int mid = (low + high) / 2;
// Check if mid no of elements
// can reach the end or not
if (possible(a, pre, mid, jumpLen))
{
// Update low to check if higher
// number of elements can reach
// the end of the array
low = mid + 1;
}
// Otherwise
else
{
// Update high
high = mid - 1;
}
}
// Return the maximum
return low - 1;
}
// Driver Code
public static void main(String[] args)
{
int x = 2;
int []a = { 1, 1, 1, 1, 1, 1 };
System.out.print(findMax(a, x));
}
}
// This code is contributed by Rohit_ranjan
Python3
import math
# Python 3 Program to implement
# the above approach
class GFG :
# Function to check if mid elements
# can reach the end of the array or not
@staticmethod
def possible( a, pre, mid, jump) :
# Size of the vector
n = len(a)
# Sum of the first window of length jump
ans = pre[min(n - 1,jump - 1)]
i = jump
while (i < n) :
# Extract the minimum sum of
# length jump from all windows
# of the array
if (i >= jump) :
ans = min(ans,pre[i] - pre[i - jump])
else :
ans = pre[i]
i += 1
if (ans >= mid) :
return True
else :
return False
# Function to count the maximum
# number of elements that can reach the
# end of the array
@staticmethod
def findMax( a, jumpLen) :
# Size of the array
n = len(a)
# Stores the prefix sums
pre = [0] * (n)
# Compute the prefix array
# from the given array
pre[0] = a[0]
i = 1
while (i < n) :
pre[i] = pre[i - 1] + a[i]
i += 1
# Initialising low and high
low = 1
high = pre[n - 1]
# Perform binary search
while (low <= high) :
# Calculate mid
mid = int((low + high) / 2)
# Check if mid no of elements
# can reach the end or not
if (GFG.possible(a, pre, mid, jumpLen)) :
# Update low to check if higher
# number of elements can reach
# the end of the array
low = mid + 1
else :
# Update high
high = mid - 1
# Return the maximum
return low - 1
# Driver Code
@staticmethod
def main( args) :
x = 2
a = [1, 1, 1, 1, 1, 1]
print(GFG.findMax(a, x), end ="")
if __name__=="__main__":
GFG.main([])
# This code is contributed by aadityaburujwale.
C#
// C# Program to implement the above approach
using System;
public class GFG {
// Function to check if mid elements can reach the end
// of the array or not
static bool possible(int[] a, int[] pre, int mid,
int jump)
{
// Size of the vector
int n = a.Length;
// Sum of the first window of length jump
int ans = pre[(Math.Min(n - 1, jump - 1))];
for (int i = jump; i < n; ++i) {
// Extract the minimum sum of length jump from
// all windows of the array
if (i >= jump) {
ans = Math.Min(ans, pre[i] - pre[i - jump]);
}
else
ans = pre[i];
}
if (ans >= mid)
return true;
else
return false;
}
// Function to count the maximum number of elements that
// can reach the end of the array
static int findMax(int[] a, int jumpLen)
{
// Size of the array
int n = a.Length;
// Stores the prefix sums
int[] pre = new int[n];
// Compute the prefix array from the given array
pre[0] = a[0];
for (int i = 1; i < n; ++i) {
pre[i] = pre[i - 1] + a[i];
}
// Initialising low and high
int low = 1, high = pre[n - 1];
// Perform binary search
while (low <= high) {
// Calculate mid
int mid = (low + high) / 2;
// Check if mid no of elements can reach the end
// or not
if (possible(a, pre, mid, jumpLen)) {
// Update low to check if higher number of
// elements can reach the end of the array
low = mid + 1;
}
// Otherwise
else {
// Update high
high = mid - 1;
}
}
// Return the maximum
return low - 1;
}
static public void Main()
{
// Code
int x = 2;
int[] a = { 1, 1, 1, 1, 1, 1 };
Console.Write(findMax(a, x));
}
}
// This code is contributed by lokesh.
JavaScript
function possible(a, pre, mid, jump) {
// Size of the array
let n = a.length;
// Sum of the first window of length jump
let ans = pre[Math.min(n - 1, jump - 1)];
for (let i = jump; i < n; ++i) {
// Extract the minimum sum of
// length jump from all windows
// of the array
if (i >= jump) {
ans = Math.min(ans, pre[i] - pre[i - jump]);
} else {
ans = pre[i];
}
}
// If the minimum sum is greater than or equal to mid
// it means mid elements can
// reach the end
if (ans >= mid) return true;
else return false;
}
// Function to count the maximum
// number of elements that can reach the
// end of the array
function findMax(a, jumpLen) {
// Size of the array
let n = a.length;
// Stores the prefix sums
let pre = Array(n);
// Compute the prefix array
// from the given array
pre[0] = a[0];
for (let i = 1; i < n; ++i) {
pre[i] = pre[i - 1] + a[i];
}
// Initialising low and high
let low = 1, high = pre[n - 1];
// Perform binary search
while (low <= high) {
// Calculate mid
let mid = Math.floor((low + high) / 2);
if (possible(a, pre, mid, jumpLen)) {
low = mid + 1;
} else {
// Update high
high = mid - 1;
}
}
// Return the maximum
return low - 1;
}
// Driver Code
function main() {
let x = 2;
let a = [1, 1, 1, 1, 1, 1];
console.log(findMax(a, x));
}
main();
Time Complexity: O(N*log(sum))
Auxiliary Space: O(N)
Sliding Window Approach:
It can be observed that since elements can only jump at most X indices, the minimum sum of all the indices of X length windows determines the highest number of elements that can reach at the end of the array. Follow the below steps to solve the problem:
- Calculate the prefix sum of the given array.
- Traverse the whole prefix sum in windows of length X.
- Calculate the sum of each window and store the minimum sum.
- Finally, print that minimum sum.
Below is the implementation of above approach:
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
#define LL long long
// Function to calculate the minimum
// sum of X-length windows of the array
LL findMinSumWindow(vector<LL> pre, int jumpLen)
{
int n = pre.size();
LL ans = pre[min(n - 1, jumpLen - 1)];
for (int i = jumpLen; i < n; ++i) {
// Calculate the minimum sum
if (i >= jumpLen) {
// Update minimum
ans
= min(ans, pre[i] - pre[i - jumpLen]);
}
else
ans = pre[i];
}
return ans;
}
// Function to count the maximum
// number of elements that can reach the
// end of the array
LL findMax(vector<LL>& a, int jumpLen)
{
// Size of the array
int n = a.size();
// Stores the prefix array
vector<LL> pre(n);
// Compute the prefix sum array
pre[0] = a[0];
for (int i = 1; i < (int)a.size(); ++i) {
pre[i] = pre[i - 1] + a[i];
}
return findMinSumWindow(pre, jumpLen);
}
// Driver Code
int main()
{
int x = 2;
vector<LL> a = { 1, 1, 1, 1, 1, 1 };
cout << findMax(a, x) << endl;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to calculate the minimum
// sum of X-length windows of the array
static int findMinSumWindow(int []pre,
int jumpLen)
{
int n = pre.length;
int ans = pre[(Math.min(n - 1, jumpLen - 1))];
for(int i = jumpLen; i < n; ++i)
{
// Calculate the minimum sum
if (i >= jumpLen)
{
// Update minimum
ans = Math.min(ans, pre[i] -
pre[i - jumpLen]);
}
else
ans = pre[i];
}
return ans;
}
// Function to count the maximum
// number of elements that can reach the
// end of the array
static int findMax(int []a, int jumpLen)
{
// Size of the array
int n = a.length;
// Stores the prefix array
int []pre = new int[n];
// Compute the prefix sum array
pre[0] = a[0];
for(int i = 1; i < a.length; ++i)
{
pre[i] = pre[i - 1] + a[i];
}
return findMinSumWindow(pre, jumpLen);
}
// Driver Code
public static void main(String[] args)
{
int x = 2;
int []a = { 1, 1, 1, 1, 1, 1 };
System.out.print(findMax(a, x) + "\n");
}
}
// This code is contributed by Amit Katiyar
Python3
# Python program to implement the above approach
# Function to calculate the minimum sum of x-length
# windows of the array
def findMinSumWindow(pre, jumpLen):
n = len(pre)
ans = pre[min(n - 1, jumpLen - 1)]
for i in range(jumpLen, n):
# calculate the minimum sum
if (i >= jumpLen):
# update minimum
ans = min(ans, pre[i] - pre[i - jumpLen])
else:
ans = pre[i]
return ans
# Function to count the maximum number of elements that
# can reach the end of the array
def findMax(a, jumpLen):
# size of the array
n = len(a)
# stores the prefix array
pre = [0] * n
# compute the prefix sum array
pre[0] = a[0]
for i in range(1, n):
pre[i] = pre[i - 1] + a[i]
return findMinSumWindow(pre, jumpLen)
x = 2
a = [1, 1, 1, 1, 1, 1]
print(findMax(a, x))
# This code is contributed by karthik.
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to calculate the minimum
// sum of X-length windows of the array
static int findMinSumWindow(int []pre,
int jumpLen)
{
int n = pre.Length;
int ans = pre[(Math.Min(n - 1, jumpLen - 1))];
for(int i = jumpLen; i < n; ++i)
{
// Calculate the minimum sum
if (i >= jumpLen)
{
// Update minimum
ans = Math.Min(ans, pre[i] -
pre[i - jumpLen]);
}
else
ans = pre[i];
}
return ans;
}
// Function to count the maximum
// number of elements that can reach the
// end of the array
static int findMax(int []a, int jumpLen)
{
// Size of the array
int n = a.Length;
// Stores the prefix array
int []pre = new int[n];
// Compute the prefix sum array
pre[0] = a[0];
for(int i = 1; i < a.Length; ++i)
{
pre[i] = pre[i - 1] + a[i];
}
return findMinSumWindow(pre, jumpLen);
}
// Driver Code
public static void Main(String[] args)
{
int x = 2;
int []a = { 1, 1, 1, 1, 1, 1 };
Console.Write(findMax(a, x) + "\n");
}
}
// This code is contributed by Rohit_ranjan
JavaScript
// Function to calculate the minimum
// sum of X-length windows of the array
function findMinSumWindow(pre, jumpLen) {
let n = pre.length;
let ans = pre[Math.min(n - 1, jumpLen - 1)];
for (let i = jumpLen; i < n; ++i) {
// Calculate the minimum sum
if (i >= jumpLen) {
// Update minimum
ans = Math.min(ans, pre[i] - pre[i - jumpLen]);
} else {
ans = pre[i];
}
}
return ans;
}
// Function to count the maximum
// number of elements that can reach the
// end of the array
function findMax(a, jumpLen) {
// Size of the array
let n = a.length;
// Stores the prefix array
let pre = new Array(n);
// Compute the prefix sum array
pre[0] = a[0];
for (let i = 1; i < n; ++i) {
pre[i] = pre[i - 1] + a[i];
}
return findMinSumWindow(pre, jumpLen);
}
// Driver Code
let x = 2;
let a = [1, 1, 1, 1, 1, 1];
console.log(findMax(a, x));
Time Complexity: O(N)
Auxiliary Space: O(N)
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