欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

最多两次股票交易-Best Time to Buy and Sell Stock III

发布时间:2024/10/12 编程问答 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 最多两次股票交易-Best Time to Buy and Sell Stock III 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

 

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;} };

  

转载于:https://www.cnblogs.com/Vae1990Silence/p/4830586.html

与50位技术专家面对面20年技术见证,附赠技术全景图

总结

以上是生活随笔为你收集整理的最多两次股票交易-Best Time to Buy and Sell Stock III的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。