Minimum steps required to reach the end of Array with a given capacity
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++
#include <bits/stdc++.h>
using namespace std;
int minSteps(vector< int >& arr, int c)
{
int n = arr.size();
vector< int > pre(n, 0);
pre[0] = arr[0];
for ( int i = 1; i < n; i++)
pre[i] = pre[i - 1] + arr[i];
int curr = 0, sc = c, ans = 0;
while (1) {
int ind = lower_bound(pre.begin(), pre.end(), sc)
- pre.begin();
if (ind >= n)
return ans + n;
else if (pre[ind] == sc) {
if (ind == n - 1)
return ans + n;
curr = ind;
}
else
curr = ind - 1;
sc = c + pre[curr];
ans += (2 * (curr + 1));
}
return 0;
}
int main()
{
vector< int > v{ 8, 8, 8, 8, 8 };
int c = 10;
cout << minSteps(v, c) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
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 ;
if (pre.get(mid) >= target) {
ans = mid;
high = mid - 1 ;
}
else {
low = mid + 1 ;
}
}
return ans;
}
static int minSteps(List<Integer> arr, int c)
{
int n = arr.size();
List<Integer> pre = new ArrayList<>();
for ( int i = 0 ; i < n; i++) {
pre.add( 0 );
}
pre.set( 0 , arr.get( 0 ));
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 ) {
int ind = lower_bound(n, sc, pre);
if (ind >= n) {
return ans + n;
}
else if (pre.get(ind) == sc) {
if (ind == n - 1 )
return ans + n;
curr = ind;
}
else
curr = ind - 1 ;
sc = c + pre.get(curr);
ans += ( 2 * (curr + 1 ));
}
}
public static void main(String[] args)
{
List<Integer> v = Arrays.asList( 8 , 8 , 8 , 8 , 8 );
int c = 10 ;
System.out.println(minSteps(v, c));
}
}
|
Python3
import bisect
def minSteps(arr, c):
n = len (arr)
pre = [ 0 ] * n
pre[ 0 ] = arr[ 0 ]
for i in range ( 1 , n):
pre[i] = pre[i - 1 ] + arr[i]
curr = 0
sc = c
ans = 0
while True :
ind = bisect.bisect_left(pre, sc)
if ind > = n:
return ans + n
elif pre[ind] = = sc:
if ind = = n - 1 :
return ans + n
curr = ind
else :
curr = ind - 1
sc = c + pre[curr]
ans + = 2 * (curr + 1 )
if __name__ = = "__main__" :
v = [ 8 , 8 , 8 , 8 , 8 ]
c = 10
print (minSteps(v, c))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
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;
if (pre[mid] >= target) {
ans = mid;
high = mid - 1;
}
else {
low = mid + 1;
}
}
return ans;
}
static int minSteps(List< int > arr, int c)
{
int n = arr.Count;
List< int > pre = new List< int >();
for ( int i = 0; i < n; i++) {
pre.Add(0);
}
pre[0] = arr[0];
for ( int i = 1; i < n; i++) {
pre[i] = pre[i - 1] + arr[i];
}
int curr = 0, sc = c, ans = 0;
while ( true ) {
int ind = lower_bound(n, sc, pre);
if (ind >= n) {
return ans + n;
}
else if (pre[ind] == sc) {
if (ind == n - 1)
return ans + n;
curr = ind;
}
else
curr = ind - 1;
sc = c + pre[curr];
ans += (2 * (curr + 1));
}
}
public static void Main()
{
List< int > v = new List< int >() { 8, 8, 8, 8, 8 };
int c = 10;
Console.WriteLine(minSteps(v, c));
}
}
|
Javascript
function minSteps(arr, c) {
const n = arr.length;
const pre = new Array(n).fill(0);
pre[0] = arr[0];
for (let i = 1; i < n; i++)
pre[i] = pre[i - 1] + arr[i];
let curr = 0,
sc = c,
ans = 0;
while ( true ) {
const ind = pre.findIndex((elem) => elem >= sc);
if (ind === -1 || ind >= n)
return ans + n;
else if (pre[ind] === sc) {
if (ind === n - 1)
return ans + n;
curr = ind;
} else
curr = ind - 1;
sc = c + pre[curr];
ans += 2 * (curr + 1);
}
return 0;
}
const v = [8, 8, 8, 8, 8];
const c = 10;
console.log(minSteps(v, c));
|
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++
#include <bits/stdc++.h>
using namespace std;
int subelement(vector< int >& arr, int capacity)
{
int steps = 0;
int c = capacity;
for ( int i = 0; i < arr.size(); i++) {
if (c < arr[i]) {
steps = steps + ((i * 2) + 1);
c = capacity;
c = c - arr[i];
}
else {
c = c - arr[i];
steps++;
}
}
return steps;
}
int main()
{
vector< int > v{ 8, 8, 8, 8, 8 };
int c = 10;
cout << subelement(v, c) << endl;
return 0;
}
|
Java
import java.util.*;
class Main {
public static int subelement(List<Integer> arr, int capacity) {
int steps = 0 ;
int c = capacity;
for ( int i = 0 ; i < arr.size(); i++) {
if (c < arr.get(i)) {
steps = steps + ((i * 2 ) + 1 );
c = capacity;
c = c - arr.get(i);
} else {
c = c - arr.get(i);
steps++;
}
}
return steps;
}
public static void main(String[] args) {
List<Integer> v = new ArrayList<>(Arrays.asList( 8 , 8 , 8 , 8 , 8 ));
int c = 10 ;
System.out.println(subelement(v, c));
}
}
|
Python
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
if __name__ = = "__main__" :
v = [ 8 , 8 , 8 , 8 , 8 ]
c = 10
print (subelement(v, c))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static int subelement(List< int > arr,
int capacity)
{
int steps = 0;
int c = capacity;
for ( int i = 0; i < arr.Count; i++) {
if (c < arr[i]) {
steps = steps + ((i * 2) + 1);
c = capacity;
c = c - arr[i];
}
else {
c = c - arr[i];
steps++;
}
}
return steps;
}
public static void Main(String[] args)
{
List< int > v = new List< int >() { 8, 8, 8, 8, 8 };
int c = 10;
Console.WriteLine(subelement(v, c));
}
}
|
Javascript
function subelement(arr, capacity) {
let steps = 0;
let c = capacity;
for (let i = 0; i < arr.length; i++) {
if (c < arr[i]) {
steps = steps + ((i * 2) + 1);
c = capacity;
c = c - arr[i];
} else {
c = c - arr[i];
steps++;
}
}
return steps;
}
const v = [8, 8, 8, 8, 8]
const c = 10
console.log(subelement(v, c));
|
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
Share your thoughts in the comments
Please Login to comment...