Open In App

Maximize count of elements reaching the end of an Array

Last Updated : 15 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:
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: 
 

  1. Initialize low = 1 and high = sum of all the array elements.
  2. Compute mid between low and high
  3. If mid is less than minimum of all the X length windows, then update low = mid + 1.
  4. Otherwise, update high = mid - 1.
  5. 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();

Output
2

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:

  1. Calculate the prefix sum of the given array.
  2. Traverse the whole prefix sum in windows of length X.
  3. Calculate the sum of each window and store the minimum sum.
  4. 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));

Output
2

Time Complexity: O(N)
Auxiliary Space: O(N)


Similar Reads