
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Initial Energy Required to Cross Street in C++
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
#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