题目:
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
代码:
int maxProfit(int* prices, int pricesSize){
if (!prices || pricesSize <= 1) return 0;
int *buy=NULL, *sell=NULL, profit=0, i=0;
while (i < pricesSize) {
if (buy == NULL) { // 空仓状态
if (i+1 < pricesSize && *(prices+i) < *(prices+i+1)) { // 明天即将升价,并且保底后天可以卖出,买入建仓
buy = prices+i;
sell = prices+i+1;
}
} else { // 持仓状态
if (i+1 >= pricesSize ||*sell > *(sell+1)) { // 明天即将降价,或者当前已经是交易最后一天,卖出清仓,计算获利
profit += *sell-*buy;
buy = NULL;
} else {
sell = prices+i+1; // 后面价格仍然会升高,持仓等待
}
}
i++;
}
return profit;
}