LeetCode--309--medium--BestTimetoBuyandSellStockwithCooldown

package com.app.main.LeetCode.dynamic;

/**
 *
 * 309
 *
 * medium
 *
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
 *
 * 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) with the following restrictions:
 *
 * You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
 * After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
 * Example:
 *
 * Input: [1,2,3,0,2]
 * Output: 3
 * Explanation: transactions = [buy, sell, cooldown, buy, sell]
 *
 *
 * Created with IDEA
 * author:Dingsheng Huang
 * Date:2019/12/10
 * Time:下午9:15
 */
public class BestTimetoBuyandSellStockwithCooldown {

    public int maxProfit(int[] prices) {

        if (prices.length <= 1) {
            return 0;
        }

        int[] dp = new int[prices.length];
        dp[0] = 0;
        dp[1] = Math.max(0, prices[1] - prices[0]);
        if (prices.length <= 2) {
            return dp[1];
        }
        for (int i = 2; i < prices.length; i++) {
            int currMax = 0;
            int tmp = 0;
            for (int j = i - 1; j >= 0; j--) {
                tmp = prices[i] - prices[j];
                if ((j - 2) >= 0) {
                    tmp += dp[j - 2];
                }
                currMax = Math.max(currMax, tmp);
            }
            dp[i] = Math.max(dp[i - 1], currMax);
        }

        return dp[prices.length - 1];
    }


    public int maxProfit2(int[] prices) {

        if (prices.length <= 1) {
            return 0;
        }

        int[] dp = new int[prices.length];
        dp[0] = 0;
        dp[1] = Math.max(0, prices[1] - prices[0]);
        if (prices.length <= 2) {
            return dp[1];
        }
        dp[2] = Math.max(Math.max(prices[2] - prices[1], prices[2] - prices[0]), dp[1]);

        // dp process
        int preMax = dp[0] - prices[2];
        preMax = Math.max(Math.max(-prices[0], -prices[1]), -prices[2]);
        for (int i = 3; i < prices.length; i++) {

            dp[i] = Math.max(dp[i - 1], preMax + prices[i]);
            preMax = Math.max(preMax, dp[i - 2] - prices[i]);
        }

        return dp[prices.length - 1];
    }
}
发布了187 篇原创文章 · 获赞 26 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/huangdingsheng/article/details/103809653