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