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) {
int result = 0;
int profit = 0;
if (prices.size() < 2)
return result;
for (vector<int>::iterator it = prices.begin() + 1; it != prices.end(); ++it)
{
profit = *it - *(it-1);
if (profit > 0)
result += profit;
}
return result;
}
};
Personal Note:
实际上就是求所有上升区段的幅度和。