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

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

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

2019-11-11 07:38:40
字體:
來源:轉載
供稿:網友
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; }};
上一篇:effect經典總結

下一篇:linux

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 衡阳县| 改则县| 左权县| 耿马| 上饶市| 五莲县| 仙游县| 开远市| 正定县| 安乡县| 开远市| 镇赉县| 祁阳县| 昭平县| 揭西县| 惠东县| 海门市| 探索| 恩施市| 读书| 松原市| 寿光市| 鄂温| 古田县| 开平市| 石嘴山市| 新余市| 仁寿县| 拉萨市| 商丘市| 浦县| 阳泉市| 保亭| 晋中市| 竹溪县| 顺义区| 通化县| 禹州市| 永仁县| 阳朔县| 寿光市|