题目:
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题目来源:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
解题思路:把股票数组的股票值画成一位曲线,取每一段的单调上升区间的开头买入,结尾处卖出,多次之和就是最大的利益
《leetcode题解》中有更简单的算法,其实思想类似,只是代码短:每当当前值比前一个值大时,就将增加的值累加到maxProf中,当扫描整个数组后,即可以得到最大的收益。
#include<iostream>
#include<vector>
using namespace std;
int maxProfit(vector<int> &prices)
{
if(prices.empty())
return 0;
int lo=0,maxProf=0;
int i=0;
for(i=0;i<prices.size()-1 && prices[i]>=prices[i+1];i++)
;
if(i==prices.size()-1)
return 0;
lo=prices[i];
int increase=1;
for(int j=i;j<prices.size()-1;j++)
{
if(prices[j]>prices[j+1] && increase==1)//开始下降
{
increase=0;
maxProf+=prices[j]-lo;
lo=0;
}
if(prices[j]<prices[j+1] && increase==0)//开始上升
{
increase=1;
lo=prices[j];
}
}
if(increase==1)//如果到最后一个点仍然是上升趋势
maxProf+=prices[prices.size()-1]-lo;
return maxProf;
}
int main()
{
vector<int> prices;
prices.push_back(1);
prices.push_back(4);
prices.push_back(2);
cout<<maxProfit(prices)<<endl;
system("pause");
return 0;
}