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).
这道题就是找到数组中的递增数组。把其差值求和。
举个例子。
1,2,3,7,3,4
递增数组有[1,2,3,7]和[3,4]那么其结果为6+1=7
class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
if(n==0) return 0;
int flag = 0;
int l = 0;
int ans = 0;
int i;
for(i = 0;i<n-1;i++)
{
if(!flag)
{
if(prices[i+1]>prices[i])
{
l = prices[i];
flag = 1;
}
}
else
{
if(prices[i+1]<prices[i])
{
ans += prices[i]-l;
flag = 0;
}
}
}
if(flag)
ans += prices[i]-l;
return ans;
}
};