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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
解题思路1:暴力枚举法
class Solution {
public int maxProfit(int[] prices) {
return dfs(prices,0);
}
public int dfs(int[] prices,int n) {
if(n >= prices.length) {
//越界判断
return 0;
}
int max = 0;
for(int start = n;start < prices.length;start++) {
int maxprofit = 0;
for(int i = start + 1;i <prices.length;i++) {
if(prices[start] < prices[i]) {
int profit = dfs(prices,i + 1) + prices[i] - prices[start];
if(profit > maxprofit) {
maxprofit = profit;
}
}
}
if(maxprofit > max) {
max = maxprofit;
}
}
return max;
}
}
不出意料,超时了。。。
解题思路2:由于可以多次买入卖出,所以我们只需要在谷底买入,并在这个谷底之后的第一个顶峰卖出,多次反复便可以获得最高利益。
具体代码如下:
class Solution {
public int maxProfit(int[] prices) {
//边界判断
if(prices.length <= 0 || prices == null) {
return 0;
}
int peak = prices[0];
int valley = prices[0];
int max = 0;
int i = 0;
while(i < prices.length - 1) {
//找到谷底
while(i < prices.length - 1 && prices[i] >= prices[i + 1]) {
i++;
}
valley = prices[i];
while(i <prices.length - 1 && prices[i] <= prices[i + 1]) {
//找到谷底之后的第一个顶峰
i++;
}
peak = prices[i];
max += peak - valley;
}
return max;
}
}
解题思路3:
按照思路2的策略即贪心策略,我们可以发现,在谷底到其之后的顶峰之间的区间内,后一个数组的元素总是比前一个数组要大,所以我们可以无需利用peak跟valley两个变量便可以寻找到最大收益值
具体代码如下:
class Solution {
public int maxProfit(int[] prices) {
//边界判断
if(prices.length <= 0 || prices == null) {
return 0;
}
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;
}
}