[DP解题] 买卖股票的最佳时间问题之二
原题链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
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的解释,股票价格数组为:[7,1,5,3,6,4]
第1天的价格是7,第2天价格是1,很明显我们不会在最贵的时候买股票。所以我们在第2天买入,也就是价格等于1的时候买,第3天价格变成了5,说明有钱赚了,那么就马上卖出。这时候利润为 5-1 = 4。然后我们在第4天价格等于 3 的时候买入股票,第5天价格等于6,有钱赚,那么就马上卖出即可。这时候利润为 6-3 = 3。
总利润就是:4+3 = 7
由此我们可以得出结论,当明天的价格比今天的价格贵的时候我们今天买入,明天卖出,这样能够获取最大利润。
最简单的公式就是 0-1+5-3+6=7 当后者比前面大,我们就加,反之我们就减,最后没有-4的原因是,减去以后就不是最大利润。
package com.bean.algorithm.dp;
public class BestTimeBuyAndSellStockII2 {
public static int maxProfit(int[] prices) {
int sell=0;
int lastsell=0;
int rest=0;
for(int i=0;i<prices.length-1;i++){
lastsell=sell;
sell=Math.max(sell+prices[i+1]-prices[i],sell);
rest=Math.max(lastsell,rest);
}
return Math.max(sell,rest);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BestTimeBuyAndSellStockII2 stock = new BestTimeBuyAndSellStockII2();
int[] demo = new int[] { 7, 1, 5, 3, 6, 4 };
int result = maxProfit(demo);
System.out.println("result = " + result);
}
}
运行结果:
result = 7