最标准答案
不可以有前一项的影响,只能用来对比并不叠加
这里max设置0就会导致先行进入大于max的判断语句!
无语了,自己把问题想的太复杂了!
class Solution {
public int maxProfit(int[] prices) {
if(prices.length<2) return 0;
int[] value = new int[prices.length];
int max,min;
value[0] = 0;
value[1] = prices[1]>prices[0] ?
prices[1]-prices[0] : 0;
if(prices[0]>prices[1]){
max = prices[1]; min = prices[1];
}
else{
max = prices[1]; min = prices[0];
}
for(int i = 2;i < prices.length;i++){
if(prices[i] > max){
max = prices[i];
value[i] = max - min;
}
else if(prices[i] < min){
min = prices[i];
value[i] = value[i-1];
}
else{
value[i] = value[i-1] > prices[i]-min?
value[i-1]:prices[i]-min;
}
}
int res = 0;
for(int i = 0; i < prices.length;i++){
if(value[i] > res) res = value[i];
}
return res;
}
}