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).
思路:这次限定了次数 那么可以以某一天为分界点 在这一天之前最大的盈利和这一天之后的最大盈利 这两个盈利之和变为两次交易的最大盈利
#include <iostream> #include <vector> using namespace std; /* 思路:可以将两次分为历史和将来 从某一天开始 历史的最好盈利和将来的最好盈利 这两者的和 即为买卖两次的最佳盈利 */ int SellStockThird(vector<int>& vec) { vector<int> share(vec.size(),0); vector<int> his(vec.size(),0); vector<int> fur(vec.size(),0); int i,j=0; for(i=1;i<vec.size();i++) share[i] = vec[i]-vec[i-1]; int cur=share[0]; int sum = share[0]; for(i=1;i<vec.size();i++) { if(cur < 0) cur = share[i]; else { cur+=share[i]; his[i] = cur; } if(sum < cur) { sum = cur; his[i] = sum; } else his[i] = his[i-1]; } cur = share[share.size()-1]; sum = cur; for(i=vec.size()-2;i>=0;i--) { if(cur < 0) cur = share[i]; else { cur+=share[i]; fur[i] = cur; } if(sum < cur) { sum = cur; fur[i] = sum; } else fur[i] = fur[i+1]; } sum =0; for(i=0;i<his.size()-1;i++) if(sum < his[i]+fur[i+1]) sum = his[i]+fur[i+1]; return sum; } int main() { int array[]={12,8,10,6,15,18,10}; vector<int> vec(array,array+sizeof(array)/sizeof(int)); cout<<SellStockThird(vec); return 0; }
public int maxProfit(int[] prices) { if(prices==null || prices.length==0) return 0; int[] local = new int[3]; int[] global = new int[3]; for(int i=0;i<prices.length-1;i++) { int diff = prices[i+1]-prices[i]; for(int j=2;j>=1;j--) { local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff); global[j] = Math.max(local[j],global[j]); } } return global[2]; }
Best time to buy and sell stock 3 --- LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44725835