【Question】
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).
方法: 单调上升的时候在最小值出买,最大值出卖出去,这样的利润最大
int maxProfit(vector<int>& prices) {
int min,max,buy,sell;
int len=prices.size();
int count=0;
int i=0;
if (len==0) return 0;
while(i<len)
{
min = prices[i];
max = prices[i];
while(prices[i]<min&&i<len)
{
min = prices[i];
i++;
}
while(prices[i]>=max&&i<len)
{
max = prices[i];
i++;
}
count+=max-min;
}
return count;
}