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).
因为这道题可以多次买卖,所以只需要用差值法算出后一天减去前一天大于0的数,然后累加就可以了。
public static int maxProfit(int[] prices) {
int result = 0;
for (int i = 0; i < prices.length - 1; i++) {
int diff = prices[i + 1] - prices[i];
result += (diff > 0 ? diff : 0);
}
return result;
}