Description
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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
1 | Input: [7,1,5,3,6,4] |
Example 2:
1 | Input: [1,2,3,4,5] |
Example 3:
1 | Input: [7,6,4,3,1] |
解法
这一题可以进行多次买卖,那只要第二天的值比今天的高,就可以在今天买入赚差价,若后天的更高,可以后天再抛出,以此类推,但每次赚的都是两日价格的差价。
具体代码如下:
1 | class Solution { |