Minimum Initial Energy Required To Cross Street in C++

C++Server Side ProgrammingProgramming

Suppose we have an array where positive and negative numbers are stored. The array is representing the checkpoint from one end to another end of the streets. The positive and negative values are representing the energy at the checkpoints. The positive values can increase energy, and negative number decreases energy. We have to find the initial energy level to cross the street, such that energy level never becomes 0 or less than 0.

Suppose we have an array A = {4, -6, 2, 3}. Let the initial energy is 0. So after reaching at first check point, the energy is 4. Now, to go to the second checkpoint, energy will be 4 + (-6) = -2. So the energy is less than 0. So we have to start journey with 3. So after first one it will be 3 + 4 = 7, and after going to second checkpoint it will be 7 + (-6) = 1.

Algorithm

minInitEnergy(arr, n):
begin
   initEnergy := 0
   currEnergy := 0
   flag := false
   for i in range 0 to n, do
      currEnergy := currEnergy + arr[i]
      if currEnergy <= 0, then
         initEnergy := initEnergy + absolute value of currEnergy + 1
         currEnergy := 1
         flag := true
      end if
   done
   if flag is false, return 1, otherwise return initEnergy
end

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
int minInitEnergy(int arr[], int n){
   int initEnergy = 0;
   int currEnergy = 0;
   bool flag = false;
   for (int i = 0; i<n; i++){
      currEnergy = currEnergy + arr[i];
      if (currEnergy <= 0){
         initEnergy = initEnergy + abs(currEnergy) + 1;
         currEnergy = 1;
         flag = true;
      }
   }
   if (flag == false)
      return 1;
   else
      return initEnergy;
}
int main() {
   int A[] = {4, -6, 2, 3};
   int n = sizeof(A)/sizeof(A[0]);
   cout << "Minimum Energy: " << minInitEnergy(A, n);
}

Output

Minimum Energy: 3
raja
Published on 25-Sep-2019 16:06:20
Advertisements