有編號1-n的n個格子,機器人從1號格子順序向后走,一直走到n號格子,并需要從n號格子走出去,機器人有一個初始能量,每個格子對應一個整數Aii,表示這個格子的能量值,如果Aii > 0,機器人走到這個格子能夠獲取Aii個能量,如果Aii < 0,走到這個格子需要消耗相應的能量,如果機器人的能量 < 0,就無法繼續前進了,問機器人最少需要有多少初始能量,才能完成整個旅程,
例如:n = 5,{1,-2,-1,3,4} 最少需要2個初始能量,才能從1號走到5號格子,途中的能量變化如下3 1 0 3 7,
Input第1行:1個數n,表示格子的數量,(1 <= n <= 50000) 第2 - n + 1行:每行1個數Aii,表示格子里的能量值(-1000000000 <= Aii <= 1000000000)Output輸出1個數,對應從1走到n最少需要多少初始能量,Sample Input
5 1 -2 -1 3 4
Sample Output
2
代碼:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=scan.nextInt(); long sum=0,cnt=0; for(int i=0;i<n;i++){ sum+=a[i]; if(sum<0){ cnt+=Math.abs(sum); sum=0;//記錄過需要的能量值以后將sum置為0 } } System.out.println(cnt); } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/110942.html
標籤:其他
上一篇:發工資
下一篇:快速冪
