给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天
买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。 来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
int maxProfit(int* prices, int pricesSize){
int max = 0, pre = 0;
for(int i = 1; i < pricesSize; i++)
{
pre = (pre > 0 ? pre : 0) + prices[i] - prices[i-1];
max = pre > max ? pre : max;
}
if(max < 0) return 0;
return max;
}
int maxProfit(int* prices, int pricesSize){
int min = prices[0], max = -2147483648;
for(int i = 1; i < pricesSize; i++)
{
max = max > prices[i] - min ? max : prices[i] - min;
min = min < prices[i] ? min : prices[i];
}
if(max < 0) return 0;
return max;
}
思路:动态规划
可以记录前i天的利润,假如第j天的利润为盈利,第j+1天加入第j天的盈利;假如亏损那就不再加入,从第j天开始买入,j+1天计算盈利