最多两次股票交易-Best Time to Buy and Sell Stock III
生活随笔
收集整理的這篇文章主要介紹了
最多两次股票交易-Best Time to Buy and Sell Stock III
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
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) {if(prices.size()==0)return 0;int n=prices.size();vector<int> left(n);vector<int> right(n);int min=prices[0];int max=prices[n-1];int res=0;for(int i=1;i<n;i++){min=min<prices[i]?min:prices[i];left[i]=left[i-1]>(prices[i]-min)?left[i-1]:(prices[i]-min);}for(int j=n-2;j>=0;j--){max=max>prices[j]?max:prices[j];right[j]=right[j+1]>(max-prices[j])?right[j+1]:(max-prices[j]);}for(int i=0;i<n;i++){res=res>(left[i]+right[i])?res:(left[i]+right[i]);}return res;} };
轉(zhuǎn)載于:https://www.cnblogs.com/Vae1990Silence/p/4830586.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的最多两次股票交易-Best Time to Buy and Sell Stock III的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 定位 - CoreLocation -
- 下一篇: 张家港哪里有卖液压车的地方张家港哪里有卖