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).
给定一个数组prices, prices[i]表示第i天的股价。本题规定最多只能买卖两次,问最大收益是多少
class Solution { public: int maxProfit(vector<int> &prices) { int size=prices.size(); if(size<=1)return 0; int*back=new int[size]; int*front=new int[size]; int maxProfit=0; int minPrice=prices[0]; int maxPrice=prices[size-1]; back[size-1]=front[0]=0; // 求出以i结尾的前半段区间上买卖一次可获得最大收益 maxProfit=0; for(int i=1; i<size; i++){ int profit=prices[i]-minPrice; if(profit>maxProfit)maxProfit=profit; front[i]=maxProfit; if(prices[i]<minPrice)minPrice=prices[i]; } // 求出以i开始的后半段区间上买卖一次可获得最大收益 maxProfit=0; for(int i=size-2; i>=0; i--){ int profit=maxPrice-prices[i]; if(profit>maxProfit)maxProfit=profit; back[i]= maxProfit; if(prices[i]>maxPrice)maxPrice=prices[i]; } //求两次买卖的最大值 maxProfit=0; for(int i=0; i<size; i++){ if(i==size-1){ if(front[i]>maxProfit)maxProfit=front[i]; } else{ if(front[i]+back[i+1]>maxProfit)maxProfit=front[i]+back[i+1]; } } return maxProfit; } };
LeetCode: Best Time to Buy and Sell Stock III [123],布布扣,bubuko.com
LeetCode: Best Time to Buy and Sell Stock III [123]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/33345117