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.
此題看清題,最多倆次交易。且倆次交易不能重疊。
個人第一次思路,計算f(0,i)與f(i,n)的最大值。可知O(N^2) 代碼超時!但正確 。
int maxProfit(vector<int> &prices)
{
if(prices.size() <2 )return 0;
int max_profit = 0;
int min_val ;
for(int k = 0;k < prices.size();k++)
{
min_val = prices[0];
int profit_1 = 0;
for(int i = 1;i < k;i++)
{
if(min_val > prices[i])
{
min_val = prices[i];
}
if(profit_1 < prices[i] - min_val)
{
profit_1 = prices[i] - min_val;
}
}
min_val = prices[k];
int profit_2 = 0;
for(int i = k+1;i < prices.size();i++)
{
if(min_val > prices[i])
{
min_val = prices[i];
}
if(profit_2 < prices[i] - min_val)
{
profit_2 = prices[i] - min_val;
}
}
int val = profit_2 + profit_1;
if(max_profit < val)
{
max_profit = val;
}
}
return max_profit;
}
第二次:感覺,需要緩存。參看他人的代碼!http://www.cnblogs.com/lihaozy/archive/2012/12/19/2825525.html利用緩存,分別0--》n 計算最大利潤值。再重n--->0計算最大利潤值。
最後利用緩存值,找倆次最大和!O(n)
#include <iostream>
#include <vector>
using namespace std;
int maxProfit(vector<int> &prices);
int main()
{
int a[] = {2,1,2,0,1};
vector<int> prices(a,a+5);
cout<<maxProfit(prices)<<endl;
return 0;
}
int maxProfit(vector<int> &prices)
{
if(prices.size() <2 )return 0;
int max_profit = 0;
int min_val ;
int max_val;
vector<int> profit_left(prices.size());
vector<int> profit_right(prices.size());
profit_left[0] = 0;
profit_right[prices.size()-1] = 0;
min_val = prices[0];
int max_profit_left = 0;
for(int i = 1;i < prices.size();i++)
{
if(min_val > prices[i])
{
min_val = prices[i];
}
if(max_profit_left < prices[i] - min_val)
{
max_profit_left = prices[i] - min_val;
}
profit_left[i] = max_profit_left;
}
max_val = prices[prices.size()-1];
int max_profit_right = 0;
for(int i = prices.size()-2;i >= 0;i--)
{
if(max_val < prices[i])
{
max_val = prices[i];
}
if(max_profit_right < max_val -prices[i] )
{
max_profit_right = max_val -prices[i];
}
profit_right[i] = max_profit_right;
}
for(int i = 0; i < prices.size();i++)
{
cout<<profit_left[i] <<" "<< profit_right[i]<<endl;
if(max_profit < profit_left[i] + profit_right[i])
{
max_profit = profit_left[i] + profit_right[i];
}
}
return max_profit;
}