1.只能买卖一次,dp[i+1] = max{dp[i], prices[i+1] - minprices}
/*
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
*/
class Solution {
public:
//保存前列数据的最小值,在最小值得后面查找可能与其最大差的数据
int maxProfit(vector<int> &prices) {
int len = prices.size();
if(len <= 1)//长度小于等于1,可能0可能只有一个数据
return 0;
int result = prices[1] - prices[0];
int minprice = prices[0];
for(int i = 1; i < len - 1; ++ i )
{
minprice = min(minprice, prices[i]);
if(result < prices[i+1] - minprice)
result = prices[i+1] - minprice;
}
if(result < 0)//很可能是【2,1】,特殊情况的处理
return 0;
else
return result;
}
};
2.一次买一次卖可以进行多次,最大收益
//找到递增递减区间,求差值,麻烦
class Solution {
public:
int maxProfit(vector<int> &prices) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int len = prices.size();
if(len <= 1)return 0;
int i = 0;
int res = 0;
while(i < len - 1)
{
int buy, sell;
while(i+1 < len && prices[i+1] < prices[i])i++;//递减区间
buy = i++;//buy是递减的最小值
while(i < len && prices[i] >= prices[i-1])i++;//递增区间
sell = i-1;//sell是递增的最大值
res += prices[sell] - prices[buy];
}
return res;
}
};
同上一题构建股票差价数组,把数组中所有差价为正的值加起来就是最大利润了。其实这和算法1差不多,因为只有递增区间内的差价是正数,并且同一递增区间内所有差价之和 = 区间最大价格 - 区间最小价格
//利用区间内所有差价之和
class Solution {
public:
int maxProfit(vector<int> &prices) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int len = prices.size();
if(len <= 1)return 0;
int res = 0;
for(int i = 0; i < len - 1 ;++ i)
{
if(prices[i] < prices[i+1])
res += prices[i+1] - prices[i];
}
return res;
}
};
3.只能交易两次,就是在数组中找两队最小最大值,前一个区间和后一个区间[0,1,....,i] [i+1,.....,n];
dp[i-1] = max{dp[i], maxprices - prices[i-1]} ,maxprices是区间[i,i+1,...,n-1]内的最高价格
class Solution {
public:
int maxProfit(vector<int> &prices) {
int len = prices.size();
if(len <= 1)
return 0;
int maxprofit = 0;
int minprice = prices[0];
int maxFromHead[len];//用一个数组保存从头到i的最大差值
maxFromHead[0] = 0;
for(int i = 1; i < len; ++ i)//错在i的值不是i<len-1
{
minprice = min(prices[i], minprice);
if(prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
maxFromHead[i] = maxprofit;
}
maxprofit = 0;
int result = maxFromHead[len - 1];
int maxprice = prices[len - 1];
for(int j = len - 2; j >= 0; -- j)//错在j的值,不是j>1,
{//从后往前计算最大差值,并且与j位置的前序最大差值相加得到result
maxprice = max(maxprice, prices[j]);
if( maxprice - prices[j] > maxprofit)
maxprofit = maxprice - prices[j];
if(maxprofit + maxFromHead[j] > result)
result = maxprofit + maxFromHead[j];
}
return result;
}
};
http://www.cnblogs.com/TenosDoIt/p/3436457.html