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 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 int ret = 0, size = prices.size(); 5 for(size_t i = 1; i < size; i++) { 6 ret += max(prices[i] - prices[i - 1], 0); 7 } 8 return ret; 9 } 10 };