Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: dora

本题只能进行一次的股票交易,所以可以采用最简单的算法。

方法一

maxprofit,min_price来记录最大获利和最小价格 maxprofit = max(maxprofit,prices[i]-min_price); min_price = min(prices[i],min_price);

方法二 动态规划

dp[i]:第i天卖掉的话最多获利多少 dp[i] = max(dp[i-1,prices[i]-min_price);

min_price = min(prices[i],min_price); min_price:到第i天之前的最低股票价格

return dp[j]//最后一天的获利数目

方法三

dp[i][0]表示持有股票时候,手里的货币数目 dp[i][1]表示卖掉股票,手里的货币数目

dp[i][0] = max(dp[i-1][0],-prices[i]);//当前的股票价格比当前股票少的时候才买入

dp[i][1] = max(dp[i-1][0]+prices[i],prices[i-1][1]);//按照当前价格卖掉手里股票的话,获利和昨天的获利比那个大,保留大的那个

return dp[n][1] //第n天后卖掉股票的手里货币数目


Comments

There are no comments at the moment.