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天的价格。设计算法获取最大的利润。可以进行多次交易,但是在再次买股票前必须卖掉之前的股票。
算法分析
方法一:
如图一所示,找出一个相邻的波峰和波谷,求波峰波谷的差值即为利润,将所有的利润相加即可。
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;
}
}