问题描述:
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
链接:https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2zsx1/
来源:LeetCode
问题分析:其实无论价格走势是一直升,还是升降兼续,最大利润永远是最大连续上升值之和。这画一个折线图就能看明白。
具体实现:
int maxProfit(int* prices, int pricesSize){
if(!prices || pricesSize < 2) return 0;
int index = 0, total = 0, ori = 0, fin = 0;
while(index < pricesSize - 1){
while(index < pricesSize - 1 && prices[index] >= prices[index+1]) index++;
ori = prices[index];
while(index < pricesSize - 1 && prices[index] <= prices[index+1]) index++;
fin = prices[index++];
total += (fin - ori);
}
return total;
}
代码说明:
1.最大的while循环控制价格上升段数,里层的第一个while循环用以寻找每一上升段的起点价格(ori),里层第二个while循环用以寻找每一上升段终点价格(fin)。
2.total用以累加每个上升段的利润,其即最终最大利润。
3.注意数组越界情况以及空数组情况,增强程序健壮性。