Best Time to Buy and Sell Stock III
解題思路來自:https://blog.csdn.net/u012501459/article/details/46514309
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
即是每天的股票價格,交易兩次,問最大收益。
解法1:
這個問題可以轉換成Best Time to Buy and Sell Stock I問題。
兩次股票交易的核心是可以定義一個交易點,在這個交易點之前可以做一次交易(賺的最大數目的錢為firstProf),在這個交易點之后可以做一個交易(賺的最大數目的錢是secondProf)。那么要求的是max(firstProf+secondProf)。但是這個方法的時間復雜度是O(N^2),空間復雜度是O(1)。leetcode中顯示超時。
可以使用兩次掃描的方法避免上面的雙重循環。
不同于Best Time to Buy and Sell Stock I中定義的初始狀態A[i]表示第i天賣出掙的最大數目的錢,這個更進一步直接定義A[i]表示前i天賺的最大數目的錢。minPrice表示從第0天到第i-1天中的最低價格。
A[0]=0。(初始狀態)
A[1]=max(prices[1]-prices[0],A[0])
A[2]=max(prices[2]-minPrice,A[1])
…..
即A[i]=max(price[i]-minPrice,A[i-1]).
A[0]=0
另外一次掃描從數組后向前掃描,定義B[i]表示從第i天到最后一天n能賺的最大數目的錢。maxPrice表示第i+1天到n天的最高價格。
B[n]=0。(初始狀態)
B[n-1]=max(maxPrice-prices[n-1],B[n])
B[n-2]=max(maxPrice-prices[n-2],B[n-1])
…..
即B[i]=max(maxPrice-prices[i],B[i+1])
B[n]=0
那么以第i天為分割點能賺的最多數目的錢為A[i]+B[i]
解題思路2:
這個比較厲害,就不寫python代碼了,了解一下就行了。
在Discuss中看到一種很棒的解法,代碼只有10行左右,但是不是很好理解。
第二種解法的核心是假設手上最開始只有0元錢,那么如果買入股票的價格為price,手上的錢需要減去這個price,如果賣出股票的價格為price,手上的錢需要加上這個price。
它定義了4個狀態:
Buy1[i]表示前i天做第一筆交易買入股票后剩下的最多的錢;
Sell1[i]表示前i天做第一筆交易賣出股票后剩下的最多的錢;
Buy2[i]表示前i天做第二筆交易買入股票后剩下的最多的錢;
Sell2[i]表示前i天做第二筆交易賣出股票后剩下的最多的錢;
那么Sell2[i]=max{Sell2[i-1],Buy2[i-1]+prices[i]}
Buy2[i]=max{Buy2[i-1],Sell[i-1]-prices[i]}Sell1[i]=max{Sell[i-1],Buy1[i-1]+prices[i]}Buy1[i]=max{Buy[i-1],-prices[i]}可以發現上面四個狀態都是只與前一個狀態有關,所以可以不使用數組而是使用變量來存儲即可。
class Solution { public: int maxProfit(vector<int>& prices) { int buy1=numeric_limits<int>::min(); int buy2=numeric_limits<int>::min(); int sell1=0; int sell2=0; for(int i=0;i<prices.size();i++) { sell2=max(sell2,buy2+prices[i]); buy2=max(buy2,sell1-prices[i]); sell1=max(sell1,buy1+prices[i]); buy1=max(buy1,-prices[i]); } return sell2; } };總結
以上是生活随笔為你收集整理的Best Time to Buy and Sell Stock III的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓Android源码——ipcamer
- 下一篇: Kubernetes安装dashboar