Wrong answer:Input: [2,1]Output: 1Expected: 0但是在本地运行输出结果却是0public class Solution { public int maxProfit(int[] A) { int maxProfit = 0; int low = A[0]; if(A.length < 2){ return 0; } for(int i = 1 ; i < A.length ; i++){ if(A[i] > low){ maxProfit = maxProfit + A[i] - low; low = A[i]; }else{ low = A[i]; } } System.out.println(maxProfit); return maxProfit; }
public class Solution { public int maxProfit(int[] A) { int maxProfit = 0; if(A.length < 2){ return 0; } int low = A[0]; for(int i = 1 ; i < A.length ; i++){ if(A[i] > low){ maxProfit = maxProfit + A[i] - low; } low = A[i]; } System.out.println(maxProfit); return maxProfit; } }
和上面一样的错误;
参考了discuss里面,这个完全复制黏贴证实可以通过,只是我不知道我错在哪里啊:
public class Solution { public int maxProfit(int[] prices) { int total = 0; for (int i=0; i< prices.length-1; i++) { if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i]; } return total; }
这个却也是可以通过:
public class Solution {
public int maxProfit(int[] A) {
int maxProfit = 0;
if(A.length < 2){
return 0;
}
int low = A[0];
for(int i = 1 ; i < A.length ; i++){
if(A[i] > low){
maxProfit = maxProfit + A[i] - low;
}
low = A[i];
}
return maxProfit;
}
}
Best Time to Buy and Sell Stock II
最新推荐文章于 2014-05-20 11:39:58 发布