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

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

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

2019-11-11 06:18:45
字體:
來源:轉載
供稿:網友
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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 增城市| 濮阳市| 三都| 嘉峪关市| 武强县| 台中市| 阆中市| 民县| 手机| 辽中县| 衡山县| 藁城市| 承德市| 卓尼县| 镇雄县| 镇远县| 大邑县| 梁平县| 南宫市| 唐海县| 高密市| 呼图壁县| 卢氏县| 苏尼特左旗| 连山| 蒙阴县| 恩平市| 改则县| 高平市| 阿勒泰市| 鄢陵县| 五台县| 民勤县| 太白县| 凌海市| 蕲春县| 涪陵区| 平安县| 祥云县| 蕲春县| 滨海县|