国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

123. Best Time to Buy and Sell Stock III(同小米風口的豬)

2019-11-11 06:50:23
字體:
來源:轉載
供稿:網友
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).

這道題實際上就是最大差值問題。之一更新最小值或最大值,以及當前最大差值即可。

這道題由于是兩次購入,所有分別從左右兩端求得然后相加即可。

class Solution {public: int maxProfit(vector<int>& prices) { int res = 0; const int size = prices.size(); if(size == 0) return res; vector<int> vec(size, 0); //從左往右計算vec[i](vec1[i])表示,第1..i+1天的最大收益,因為數組下標從零開始 int min = prices[0]; for(int i=1; i<size; ++i){ vec[i] = vec[i-1]; //如果收益沒有之前的多,至少要保持 if(prices[i] - min > vec[i]) //以當天為界限,計算之前的最大收益,所以是減 vec[i] = prices[i] - min; if(prices[i] < min) min = prices[i]; } //從右往左計算vec2[i]表示,第i+1天到最后一天的最大收益 //這里由于采用vec2[i]空間復雜度為O(2n),所以利用profit變量省去vec2[i],直接在vec[i]上相加即可 int max = prices[size-1], profit = 0; for(int i=size-2; i>=0; --i){ if(max - prices[i] > profit) //以當天為界,未來的最大收益,則是更遠的天數減去更近的天數 profit = max - prices[i]; vec[i] += profit; //在這里直接+=,直接將之前算的某天以前的最大收益和目前某天以后最大收益相加,節省空間復雜度 if(prices[i] > max) max = prices[i]; } for(int i=0; i<size; ++i) //找出某一天滿足最大收益最大 res = std::max(res, vec[i]); return res; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁津县| 开远市| 赤峰市| 余姚市| 从江县| 凉山| 巴南区| 陕西省| 临泉县| 曲靖市| 湘阴县| 栾川县| 资兴市| 务川| 云龙县| 灯塔市| 二连浩特市| 东台市| 贵溪市| 翁牛特旗| 华池县| 句容市| 兰西县| 太仓市| 中阳县| 高台县| 潍坊市| 庄河市| 秀山| 南丰县| 张家界市| 探索| 云浮市| 邵东县| 耒阳市| 休宁县| 新昌县| 宁陕县| 方山县| 绥中县| 淅川县|