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).
給定一個數組,第i個元素代表第i天的價格。設計算法獲取最大的利潤??梢赃M行多次交易,但是在再次買股票前必須賣掉之前的股票。
算法分析
方法一:
如圖一所示,找出一個相鄰的波峰和波谷,求波峰波谷的差值即為利潤,將所有的利潤相加即可。
圖一:最大利潤
Java代碼
public class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int i = 0;
//int valley = prices[0];
//int peak = prices[1];
while (i < prices.length - 1) {
while (i < prices.length - 1 && prices[i] >= prices[i + 1])//找出波谷
i ++;
int valley = prices[i];
while (i < prices.length - 1 && prices[i] <= prices[i + 1])//找出波峰
i ++;
int peak = prices[i];
maxProfit += peak - valley;
}
return maxProfit;
}
}
方法二:
如圖一圖二所示:
圖二:最大利潤
不管是哪種情況,只要今天的價格比昨天高,就獲得這部分利潤,最后將所有的利潤相加,一定是最大利潤。
Java代碼
public class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
for (int i = 1; i < prices.length; i ++) {
if (prices[i] > prices[i - 1])//如果今天比昨天的值大,就計算一次
maxProfit += (prices[i] - prices[i - 1]);
}
return maxProfit;
}
}