Problem:
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).
Analysis:
Solutions:
C++:
int maxProfit(vector<int>& prices)
{
int maxValue = 0;
vector<int> v_profits;
v_profits.push_back(0);
int max_profit = 0;
for(int i = 1; i < prices.size(); ++i)
v_profits.push_back(prices[i] - prices[i - 1]);
for(int i = 0; i < v_profits.size(); ++i)
max_profit += (v_profits[i] > 0 ? v_profits[i] : 0);
return max_profit;
}
Java:
Python: