方法一,自己想的
本题中可以多次买入股票,那么:
- 如果第二天股票涨了并且还没有买入:选择买入,因为一定可以盈利(可能是明天卖,也可能是未来某一天价格更高的时候卖)
- 如果第二天股票跌了并且已经买入了:选择卖出(今天卖了之后可以拿明天低成本的筹码,最差的情况就是明天当天卖当天买,起码不会亏钱)
public int maxProfit(int[] prices) {
int len = prices.length;
int profit = 0;
int buyFlag = 0;
int buyPrice = 0;
int salePrice = 0;
for (int i = 0; i < len-1; i++) {
if (buyFlag == 0) {
if (prices[i] < prices[i + 1]) {
// 第二天价格涨了
buyPrice = prices[i]; // 有盈利空间,买入
buyFlag = 1;
}
}else{
if (prices[i] > prices[i + 1]) {
// 明天降价了,今天卖出
salePrice = prices[i];
profit = profit + salePrice - buyPrice;
buyFlag = 0;
}
}
}
// 手中还有股票没有卖出
if(buyFlag==1 && prices[len-1] > buyPrice){
profit = profit + prices[len-1] - buyPrice;
}
return profit;
}
方法二
由于没有手续费以及不限制交易次数,所以只要比昨天价格高今天就进行买入卖出,这样就可以把所有利润收入囊中
public int maxProfit222(int[] prices) {
// 由于不限制交易次数,所以比昨天价格高今天进行买入卖出,这样就可以把所有利润收入囊中
int res = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i-1]) {
res += prices[i] - prices[i-1];
}
}
return res;
}