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).
把问题想清楚,其实就是算整个区间内所有上升段的长度总和,所以其实解起来挺简单。
class Solution {
public:
int maxProfit(vector<int> &prices) {
vector<int>::iterator it = prices.begin();
if (prices.size() < 2)
return 0;
int res = 0;
while (it != prices.end() - 1 )
{
if (*it < *(it+1))
res += *(it+1) - *it;
it++;
}
return res;
}
};