标签:des c style class blog code
Problem Description:
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).
按照题意,要求根据每天的股票价格,交易两次得到最大的利润。直接的想法就是利用分治法,从前往后循环依次将数组分为前后两个股票价格序列,分别得到最大的利润,将两者相加得到两次交易的最大利润,时间复杂度O(n^2),提交果然超时了。
代码如下:
class Solution { public: int profit(vector<int> &vec,int beg,int last) { int res=0; if(beg==last) return res; int min=vec[beg]; for(int i=beg+1;i<=last;++i) { if(vec[i]>min) { int temp=vec[i]-min; if(temp>res) res=temp; } else min=vec[i]; } return res; } int maxProfit(vector<int> &prices) { int res=0; int n=prices.size(); if(n<=1) return res; for(int i=1;i<n-1;i++) { int res1=profit(prices,0,i); int res2=profit(prices,i+1,n-1); if((res1+res2)>res) res=res1+res2; } return res; } };
具体代码如下:
class Solution { public: int maxProfit(vector<int> &prices) { int res=0; int n=prices.size(); if(n<=1) return res; vector<int> front(n,0); vector<int> back(n,0); int minp=prices[0]; int maxp=prices[n-1]; for(int i=1;i<n;i++) { if(prices[i]>minp) front[i]=prices[i]-minp; else minp=prices[i]; } for(int i=n-2;i>=0;i--) { if(prices[i]>maxp) maxp=prices[i]; back[i]=max(maxp-prices[i],back[i+1]); if(front[i]+back[i]>res) res=front[i]+back[i]; } return res; } };
Leetcode--Best Time to Buy and Sell Stock III,布布扣,bubuko.com
Leetcode--Best Time to Buy and Sell Stock III
标签:des c style class blog code
原文地址:http://blog.csdn.net/longhopefor/article/details/27340055