Problem Description
There are n grids numbered 1-n. The robot walks backwards from grid 1 to grid n, and needs to go out from grid n. The robot has an initial energy, and each grid corresponds to an integer A[i], which represents the energy value of this grid. If A[i] > 0, the robot can get A[i] energy by walking to this grid. If A[i] < 0, it needs to consume the corresponding energy when walking to this grid. If the robot's energy is < 0, it cannot continue. Go ahead. Ask how much initial energy the robot needs to have to complete the entire journey.
For example: n = 5. {1, -2, -1, 3, 4} requires at least 2 initial energies to go from square 1 to square 5. The energy change on the way is as follows 3 1 0 3 7.
Input
Line 1: 1 number n, representing the number of grids. (1 <= n <= 50000)
Line 2 - n + 1: 1 number A[i] in each line, representing the energy value in the grid (-1000000000 <= A[i] <= 1000000000)
Output
Output 1 number, corresponding to the minimum initial energy required to go from 1 to n.
Sample Input
5
1
-2
-1
3
4
Sample Output
2
AC code
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int minenergy=0,sum=0;
for(int i=0;i<n;i++){
sum+=a[i];
if(sum<minenergy){
minenergy=sum;
}
}
cout<<-minenergy;
return 0;
}