LeetCode 309. Best Time to Buy and Sell Stock with Cooldown(股票交易)

来源:互联网 发布:网络协议的教学反思 编辑:程序博客网 时间:2024/05/21 15:04

原题网址: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:

prices = [1, 2, 3, 0, 2]maxProfit = 3transactions = [buy, sell, cooldown, buy, sell]

方法:动态规划。


public class Solution {    public int maxProfit(int[] prices) {        if (prices == null || prices.length < 2) return 0;        int[] lastSell = new int[prices.length];        int[] totalProfit = new int[prices.length];        for(int i=1; i<prices.length; i++) {            lastSell[i] = Math.max(0, lastSell[i-1] + (prices[i]-prices[i-1]));            if (i>=3) lastSell[i] = Math.max(lastSell[i], totalProfit[i-3] + (prices[i]-prices[i-1]));            totalProfit[i] = Math.max(lastSell[i], totalProfit[i-1]);        }        return totalProfit[prices.length-1];    }}

另一种实现:

public class Solution {    public int maxProfit(int[] prices) {        if (prices == null || prices.length <= 1) return 0;        int n = prices.length;        int[] local = new int[n];        int[] global = new int[n];        for(int i=1; i<n; i++) {            local[i] = Math.max(0, prices[i] - prices[i-1]);            local[i] = Math.max(local[i], local[i-1] + prices[i] - prices[i-1]);            if (i>=3) local[i] = Math.max(local[i], global[i-3] + prices[i]-prices[i-1]);            global[i] = Math.max(global[i-1], local[i]);        }        return global[n-1];    }}


0 0
原创粉丝点击