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).
給定一個數(shù)組剩岳,第i個元素代表第i天的價格草描。設(shè)計算法獲取最大的利潤怀跛〖鹪祝可以進行多次交易,但是在再次買股票前必須賣掉之前的股票放典。
算法分析
方法一:
如圖一所示逝变,找出一個相鄰的波峰和波谷,求波峰波谷的差值即為利潤奋构,將所有的利潤相加即可壳影。
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;
}
}