相比于上一道题目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;
}
}