121. Best Time to Buy and Sell Stock 買賣股票的最佳時機
阿新 • • 發佈:2019-03-30
urn runt span 嘗試 idt info style color width
第一想法是滑動窗口法,稍微嘗試後發現不可行,至少我不會。。。
而後想到動態規劃,進一步思考發現完全可行:
index | 0 | 1 | 2 | 3 | 4 | 5 |
price[] | 7 | 1 | 5 | 3 | 6 | 4 |
dp[] | 0 | 0 | 4 | 2 | 5 | 3 |
price[index-1] - dp[index-1] | 0 | 0 | 1 | 1 | 1 | 1 |
狀態:dp[i] 表示prices[]從 0 到 i 這部分的最大利潤
狀態轉移方程:
dp[i] = max(0, prices[i] - (prices[i-1] - dp[i-1]));
使用dp數組的代碼如下:
class Solution { public: int maxProfit(vector<int>& prices) { int ans = 0; vector<int> dp(prices.size(), 0); for(int i=1; i<prices.size();i++) { dp[i] = max(0, prices[i] - (prices[i-1] - dp[i-1])); ans = max(dp[i], ans); }return ans; } };
然而,dp數組會占用多余的空間。我們知道,一位dp問題的dp數組的賦值往往可以轉化為幾個變量之間的循環賦值的過程
所以,改進如下:
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() == 0) { return 0; } int ans = 0; int res = 0;int pre_price = prices[0]; int pre_dp = 0; for(int price : prices) { res = max(0, price - (pre_price - pre_dp)); pre_dp = res; pre_price = price; ans = max(res, ans); } return ans; } };
註意,用這種方式要先判斷size是否為0,否則會出現Runtime Error。。。
兩份代碼的Runtime都是8ms,而改進後內存占用由9.7MB減少到9.5MB,千萬別小看這0.2MB。
我們從擊敗5%的同學升級到擊敗46%的同學!
121. Best Time to Buy and Sell Stock 買賣股票的最佳時機