一 题目:
二 思路:
在某一日最低价买入,在这天之后的最高价卖出
因此我们只要找最低价并且比较最低价之后的最高价即可。
三 代码:
public int maxProfit(int[] prices) {
//前面交易日最小价格
int minPrice=prices[0];
//当前的最大收益
int maxProfit=0;
for (int i = 1; i < prices.length; i++) {
//只要当前值大于最低价就有利润,这里计算利润即可
if (prices[i]>minPrice){
maxProfit=Math.max(maxProfit,prices[i]-minPrice);
}else {
//更换最低价
minPrice=prices[i];
}
}
return maxProfit;
}