相比於上一道題目Best Time to Buy and Sell Stock,這道題目可以交易多次,那麼在從前向後掃描數組的過程中,只要後面一天的股票價格高於當今的股票價格,就進行股票的交易,相當於是使用了貪心的思想,代碼如下:
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0; // corner case
int result = 0;
for(int i = 0; i < prices.length - 1; i++){
if(prices[i + 1] > prices[i]){
result += prices[i + 1] - prices[i];
}
}
return result;
}
}