Open In App

Minimum steps required to reach the end of Array with a given capacity

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size n. You will have to traverse the array from left to right deducting each element of the array from the initial capacity, such that your initial capacity should never go below 0. In case, the current capacity is less than the current element, we can traverse back to the start of the array to refill our capacity, and then start where we left off, the task is to return the minimum number of steps required to reach the end of the array, given you are initially at the start of the array or index (-1).

Examples:

Input: arr = [3, 3, 4, 4], capacity = 7
Output: 14
Explanation: Start at the index 1:

  • Walk to index 0 (1 step) and subtract it, capacity = 4
  • Walk to index 1 (1 step) and subtract it. capacity = 1
  • Since after subtraction of element at index 2 capacity = -3 which is negative so we have to return to index -1(2 steps) and capacity becomes 7 again.
  • Walk to index 2 (3 steps) and subtract it. capacity = 3
  • Since after subtraction of element at index 3 capacity = -1 which is negative so we have to return to index -1(3 steps) and capacity becomes 7 again.
  • Walk to index 3 (4 steps) and subtract it.capacity = 3
  • Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.

Input: arr = [1, 1, 1, 4, 2, 3], capacity = 4
Output: 30
Explanation: Start at the index 1:

  • subtract arr 0, 1, and 2 (3 steps). Return to index -1(3 steps).
  • subtract arr 3 (4 steps). Return to index -1(4 steps).
  • subtract arr 4 (5 steps). Return to index -1 (5 steps).
  • subtract arr 5 (6 steps).
  • Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.

Input: arr = [8, 8, 8, 8, 8], capacity = 10
Output: 25
Explanation: You have to return to index -1 after each iteration.
Steps needed = 25.

Naive Approach: The basic way to solve the problem is as follows:

We can declare a prefix array and store the results before hand of each and every arr at place. Then using binary search we could search for our specified fruit and calculate the steps in the whole iteration.

Steps that were to follow the above approach:

  • Call minSteps function to return the minimum number of steps to reach the end of the array.
  • Create pre array which contains the prefix sum up to that point in the input array.
  • Then, loop until we reach the end of the array, and do the following:
    • Binary search for the current range we can go.
    • Add up to the answer, and return it ans+n, once the end is reached of the array.

Below is the code to implement the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
int minSteps(vector<int>& arr, int c)
{
 
    int n = arr.size();
 
    // Find the size of array
    vector<int> pre(n, 0);
 
    // Declare a prefix sum vector for
    // storing the result before hand
    pre[0] = arr[0];
 
    for (int i = 1; i < n; i++)
        pre[i] = pre[i - 1] + arr[i];
 
    // Fill the prefix sum vector
    int curr = 0, sc = c, ans = 0;
 
    while (1) {
 
        int ind = lower_bound(pre.begin(), pre.end(), sc)
                  - pre.begin();
 
        // Finding the lowerbound using
        // binary search and substracting
        // the perviously computed value
        if (ind >= n)
            return ans + n;
 
        // If index goes beyond the array
        // size then return the size
        // summed up with array size
        else if (pre[ind] == sc) {
 
            // If element at prefix array
            // is equal to source then
            // check if index has reached
            // the last element
            if (ind == n - 1)
                return ans + n;
            curr = ind;
        }
 
        else
            curr = ind - 1;
 
        sc = c + pre[curr];
 
        // Add prefix value at current
        // index to source
        ans += (2 * (curr + 1));
    }
    return 0;
}
 
// Drivers code
int main()
{
    vector<int> v{ 8, 8, 8, 8, 8 };
    int c = 10;
 
    // Function Call
    cout << minSteps(v, c) << endl;
 
    return 0;
}


Java




// Java code for the above approach
 
import java.util.*;
 
class GFG {
    // lower_bound utility function
    static int lower_bound(int n, int target,
                           List<Integer> pre)
    {
        int low = 0, high = n - 1;
        int ans = n;
 
        while (low <= high) {
            int mid = (low + high) / 2;
            // reduce the search space on the right
            // if mid element is greater than or equal to
            // target
            if (pre.get(mid) >= target) {
                ans = mid;
                high = mid - 1;
            }
            // reduce the search space on the left
            // if middle element is lesser than target
            else {
                low = mid + 1;
            }
        }
 
        return ans;
    }
 
    static int minSteps(List<Integer> arr, int c)
    {
        // Find the size of the array
        int n = arr.size();
        // Declare a prefix sum List for
        // storing the result before hand
        List<Integer> pre = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            pre.add(0);
        }
        pre.set(0, arr.get(0));
 
        // Fill the prefix sum List
        for (int i = 1; i < n; i++) {
            pre.set(i, pre.get(i - 1) + arr.get(i));
        }
 
        int curr = 0, sc = c, ans = 0;
 
        while (true) {
            // Finding the lowerbound using
            // binary search and substracting
            // the perviously computed value
            int ind = lower_bound(n, sc, pre);
 
            // If index goes beyond the array
            // size then return the size
            // summed up with array size
            if (ind >= n) {
                return ans + n;
            }
            else if (pre.get(ind) == sc) {
 
                // If element at prefix array
                // is equal to source then
                // check if index has reached
                // the last element
                if (ind == n - 1)
                    return ans + n;
                curr = ind;
            }
            else
                curr = ind - 1;
 
            sc = c + pre.get(curr);
 
            // Add prefix value at current
            // index to source
            ans += (2 * (curr + 1));
        }
    }
 
    // Drivers code
    public static void main(String[] args)
    {
        List<Integer> v = Arrays.asList(8, 8, 8, 8, 8);
        int c = 10;
 
        // Function Call
        System.out.println(minSteps(v, c));
    }
}
 
// This code is contributed by ragul21


Python3




# python code for the above approach:
 
import bisect
 
def minSteps(arr, c):
    n = len(arr)
 
    # Find the size of the array
    pre = [0] * n
 
    # Declare a prefix sum list for storing the result beforehand
    pre[0] = arr[0]
 
    for i in range(1, n):
        pre[i] = pre[i - 1] + arr[i]
 
    # Fill the prefix sum list
    curr = 0
    sc = c
    ans = 0
 
    while True:
        ind = bisect.bisect_left(pre, sc)
 
        # Finding the lower bound using binary search and subtracting
        # the previously computed value
        if ind >= n:
            return ans + n
 
        # If the index goes beyond the array size, then return the size
        # summed up with array size
        elif pre[ind] == sc:
            # If the element at the prefix array is equal to the source, then
            # check if the index has reached the last element
            if ind == n - 1:
                return ans + n
            curr = ind
        else:
            curr = ind - 1
 
        sc = c + pre[curr]
 
        # Add prefix value at the current index to the source
        ans += 2 * (curr + 1)
 
# Drivers code
if __name__ == "__main__":
    v = [8, 8, 8, 8, 8]
    c = 10
 
    # Function Call
    print(minSteps(v, c))


C#




// C# code for the above approach
 
using System;
using System.Collections.Generic;
 
public class GFG {
    // lower_bound utility function
    static int lower_bound(int n, int target, List<int> pre)
    {
        int low = 0, high = n - 1;
        int ans = n;
 
        while (low <= high) {
            int mid = (low + high) / 2;
            // reduce the search space on the right
            // if mid element is greater than or equal to
            // target
            if (pre[mid] >= target) {
                ans = mid;
                high = mid - 1;
            }
            // reduce the search space on the left
            // if middle element is lesser than target
            else {
                low = mid + 1;
            }
        }
 
        return ans;
    }
 
    static int minSteps(List<int> arr, int c)
    {
        // Find the size of array
        int n = arr.Count;
        // Declare a prefix sum vector for
        // storing the result before hand
        List<int> pre = new List<int>();
 
        for (int i = 0; i < n; i++) {
            pre.Add(0);
        }
        pre[0] = arr[0];
 
        // Fill the prefix sum list
        for (int i = 1; i < n; i++) {
            pre[i] = pre[i - 1] + arr[i];
        }
 
        int curr = 0, sc = c, ans = 0;
 
        while (true) {
            // Finding the lowerbound using
            // binary search and substracting
            // the perviously computed value
            int ind = lower_bound(n, sc, pre);
            // If index goes beyond the array
            // size then return the size
            // summed up with array size
            if (ind >= n) {
                return ans + n;
            }
            else if (pre[ind] == sc) {
 
                // If element at prefix array
                // is equal to source then
                // check if index has reached
                // the last element
                if (ind == n - 1)
                    return ans + n;
                curr = ind;
            }
            else
                curr = ind - 1;
 
            sc = c + pre[curr];
 
            // Add prefix value at current
            // index to source
            ans += (2 * (curr + 1));
        }
 
        // return 0;
    }
    // Drivers code
    public static void Main()
    {
        List<int> v = new List<int>() { 8, 8, 8, 8, 8 };
        int c = 10;
 
        // Function Call
        Console.WriteLine(minSteps(v, c));
    }
}
 
// This code is contributed by ragul21


Javascript




// JavaScript code for the above approach:
function minSteps(arr, c) {
    const n = arr.length;
 
    // Find the size of array
    const pre = new Array(n).fill(0);
 
    // Declare a prefix sum vector for
    // storing the result beforehand
    pre[0] = arr[0];
 
    for (let i = 1; i < n; i++)
        pre[i] = pre[i - 1] + arr[i];
 
    // Fill the prefix sum vector
    let curr = 0,
        sc = c,
        ans = 0;
 
    while (true) {
 
        const ind = pre.findIndex((elem) => elem >= sc);
 
        // Finding the lower bound using
        // linear search and subtracting
        // the previously computed value
        if (ind === -1 || ind >= n)
            return ans + n;
 
        // If index goes beyond the array
        // size then return the size
        // summed up with array size
        else if (pre[ind] === sc) {
 
            // If element at prefix array
            // is equal to source then
            // check if index has reached
            // the last element
            if (ind === n - 1)
                return ans + n;
            curr = ind;
        } else
            curr = ind - 1;
 
        sc = c + pre[curr];
 
        // Add prefix value at current
        // index to source
        ans += 2 * (curr + 1);
    }
    return 0;
}
 
// Drivers code
const v = [8, 8, 8, 8, 8];
const c = 10;
 
// Function Call
console.log(minSteps(v, c));


Output

25










Time Complexity: O(n + log n), this is for prefix sum and then binary search.
Auxiliary Space: O(n), for declaring a prefix array.

Efficient Approach: To solve the problem follow the below idea:

We can substract elements going in order from left to right and get back to index -1 once capacity becomes negative and calculate the whole iteration of going to index -1 and coming back to the unsubstracted element. This will be a simple linear traversal.

Steps to implement the above approach:

  • Loop over the entire array from left to right and do the following:
    • If the current capacity is less than the current array element,  
      • increase steps for both-way movement, and add 1 to move to the next element.
    • else, increment the steps and subtract the element from the total capacity left.
  • Finally, return the total number of steps traveled.

Below is the code to implement the above approach:

C++




// C++ Code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
int subelement(vector<int>& arr, int capacity)
{
    int steps = 0;
 
    // Declare a steps variable for
    // keeping the count of steps
    int c = capacity;
    for (int i = 0; i < arr.size(); i++) {
        if (c < arr[i]) {
 
            // If our capapcity is less
            // than current array element
            // increment the steps for
            // bi-directional traversal
            // and adding 1 to move to
            // next element
            steps = steps + ((i * 2) + 1);
            c = capacity;
 
            // Making the capacity element
            // as it was originally
            c = c - arr[i];
 
            // Subtracting the current
            // position value from
            // capacity
        }
        else {
            c = c - arr[i];
 
            // If capacity is greater than
            // current element we simply
            // subtract the same from
            // capacity
            steps++;
 
            // Incrementing the steps
            // for each iteration
        }
    }
    return steps;
}
 
// Drivers code
int main()
{
    vector<int> v{ 8, 8, 8, 8, 8 };
    int c = 10;
 
    // Function Call
    cout << subelement(v, c) << endl;
 
    return 0;
}


Java




// Java code for the above approach
 
import java.util.*;
 
class Main {
    public static int subelement(List<Integer> arr, int capacity) {
        int steps = 0;
         
        // Declare a steps variable for
        // keeping the count of steps
        int c = capacity;
        for (int i = 0; i < arr.size(); i++) {
            if (c < arr.get(i)) {
                // If our capacity is less
                // than the current array element
                // increment the steps for
                // bi-directional traversal
                // and add 1 to move to
                // next element
                steps = steps + ((i * 2) + 1);
                c = capacity;
 
                // Making the capacity element
                // as it was originally
                c = c - arr.get(i);
 
                // Subtracting the current
                // position value from
                // capacity
            } else {
                c = c - arr.get(i);
 
                // If capacity is greater than
                // current element, we simply
                // subtract the same from
                // capacity
                steps++;
 
                // Incrementing the steps
                // for each iteration
            }
        }
        return steps;
    }
     
    public static void main(String[] args) {
        List<Integer> v = new ArrayList<>(Arrays.asList(8, 8, 8, 8, 8));
        int c = 10;
         
        // Function call
        System.out.println(subelement(v, c));
    }
}
 
// This code is contributed by Vaibhav Nandan


Python




# Nikunj Sonigara
 
def subelement(arr, capacity):
    steps = 0
    c = capacity
     
    for i in range(len(arr)):
        if c < arr[i]:
            steps = steps + ((i * 2) + 1)
            c = capacity
            c = c - arr[i]
        else:
            c = c - arr[i]
            steps += 1
     
    return steps
 
# Driver code
if __name__ == "__main__":
    v = [8, 8, 8, 8, 8]
    c = 10
     
    # Function Call
    print(subelement(v, c))


C#




// C# code for the above approach
 
using System;
using System.Collections.Generic;
 
public class GFG {
    public static int subelement(List<int> arr,
                                 int capacity)
    {
        int steps = 0;
        // Declare a steps variable for
        // keeping the count of steps
        int c = capacity;
        for (int i = 0; i < arr.Count; i++) {
            if (c < arr[i]) {
                // If our capacity is less
                // than the current array element
                // increment the steps for
                // bi-directional traversal
                // and add 1 to move to
                // next element
                steps = steps + ((i * 2) + 1);
                c = capacity;
 
                // Making the capacity element
                // as it was originally
                c = c - arr[i];
 
                // Subtracting the current
                // position value from
                // capacity
            }
            else {
                c = c - arr[i];
 
                // If capacity is greater than
                // current element, we simply
                // subtract the same from
                // capacity
                steps++;
 
                // Incrementing the steps
                // for each iteration
            }
        }
        return steps;
    }
 
    public static void Main(String[] args)
    {
        List<int> v = new List<int>() { 8, 8, 8, 8, 8 };
        int c = 10;
 
        // Function call
        Console.WriteLine(subelement(v, c));
    }
}
 
// This code is contributed by ragul21


Javascript




// Javascript code for the above approach
 
function subelement(arr, capacity) {
    let steps = 0;
    // Declare a steps variable for
    // keeping the count of steps
    let c = capacity;
    for (let i = 0; i < arr.length; i++) {
        if (c < arr[i]) {
            // If our capacity is less
            // than the current array element
            // increment the steps for
            // bi-directional traversal
            // and add 1 to move to
            // next element
            steps = steps + ((i * 2) + 1);
            c = capacity;
 
            // Making the capacity element
            // as it was originally
            c = c - arr[i];
 
            // Subtracting the current
            // position value from
            // capacity
        } else {
            c = c - arr[i];
 
            // If capacity is greater than
            // current element, we simply
            // subtract the same from
            // capacity
            steps++;
 
            // Incrementing the steps
            // for each iteration
        }
    }
    return steps;
}
 
 
const v = [8, 8, 8, 8, 8]
const c = 10
 
console.log(subelement(v, c));
 
// This code is contributed by ragul21


Output

25










Time Complexity: O(n), this is due to linear traversal.
Space Complexity: O(1), as we don’t need any extra space.



Last Updated : 18 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads