一 题目:
二 思路:
在谷底买入,峰值出售,如果是一段一直下降的曲线就不要买
对于连续上涨交易日: 设此上涨交易日股票价格分别为 p 1 ,p 2 ,...,p n ,则第一天买最后一天卖收益最大,即 p n −p 1 ;等价于每天都买卖,即 p n −p 1 =(p 2 −p 1 )+(p 3 −p 2 )+...+(p n −p n−1 )。
遍历整个股票交易日价格列表 price,并执行贪心策略:所有上涨交易日都买卖(赚到所有利润),所有下降交易日都不买卖(永不亏钱)。
三 代码:
public int maxProfit(int[] prices) {
int prePrice=prices[0];
int money=0;
for (int i = 1; i < prices.length; i++) {
//只要对比前一天我们是赚的就卖
if (prices[i]>prePrice){
money+=prices[i]-prePrice;
}
prePrice=prices[i];
}
return money;
}