leetcode.com/problems/best-time-to-buy-and-sell-stock/
MaxProfit[n] : 若第n天卖出,能获得的最大收益。
Price[n]: 第n天的股票价格。
递推式为
MaxProfit[n] = max(MaxProfit[n-1] + Price[n] - Price[n-1], 0)
示例实现
int maxProfit(int* prices, int pricesSize) {
int maxProfit = 0;
int maxProfitToday = 0;
int i = 0;
for (i=0; i < pricesSize ;i++) {
if (i == 0) {
maxProfit = 0;
maxProfitToday = 0;
continue;
}
if (maxProfitToday + prices[i] - prices[i-1] > 0) {
maxProfitToday = maxProfitToday + prices[i] - prices[i-1];
} else {
maxProfitToday = 0;
}
maxProfit = maxProfit > maxProfitToday ? maxProfit : maxProfitToday;
}
return maxProfit;
}