Best Time to Buy and Sell Stock II--疑惑
https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
代码如下时能AC
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 int p=0; 5 for(int i = 1; i < prices.size() ; ++i) { 6 int delta = prices[i] - prices[i-1]; 7 if(delta > 0 ) { 8 p += delta; 9 } 10 } 11 return p; 12 } 13 };
但是,代码如下时却Runtime Error,提示Last executed input:[]
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 int p=0; 5 for(int i = 0; i < prices.size()-1 ; ++i) { 6 int delta = prices[i+1] - prices[i]; 7 if(delta > 0 ) { 8 p += delta; 9 } 10 } 11 return p; 12 } 13 };
这代码明明跟这段Java是一样的啊。这Java代码也能AC。奇怪。
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 int total = 0; 4 for (int i=0; i< prices.length-1; i++) { 5 if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i]; 6 } 7 8 return total; 9 }
最后只能是加入一行
1 if(prices.size()==0) return 0;
来保证edge case.
——————————————————————————————————————————————————————————————————————
This problem is solved by Shangrila finally:
Replace prices.size()-1
by int(prices.size())-1
. The type of prices.size()
is SIZE_T, which is unsigned integer types. -1 could overflow.