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).
这题比较简单,因为可以无限次买卖,因此只要比较连续两天的价格差,只要是正的就把这个价格差加到结果上。
public class Solution {
public int maxProfit(int[] prices) {
int result = 0;
int diff = 0;
for(int i = 0; i < prices.length - 1; i++){
diff = prices[i + 1] - prices[i];
if(diff > 0)
result += diff;
}
return result;
}
}