leetcode Best Time to Buy and Sell Stock with Cooldown - 细语呢喃
leetcode 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: maxProfit = 3 transactions = [buy, sell, cooldown, buy, sell] 你每次只能买一件而且在再次买入之前必须出售之前手头上的物品(就是手头上最多有一件物品) Idea DP,we can create two array, buy and sell. buy[i] means we buy a stock at day i , and sell[i] means we sell a stock at day i. so, we have twoequations : buy[i] = max(buy[i-1] , sell[i-2] – prices[i]) // So we should use sell[i-2] means we cooldown one day. sell[i] = max(sell[i-1], buy[i-1] + prices[i]) finally, return the max(buy[n-1] ,Read full article from leetcode Best Time to Buy and Sell Stock with Cooldown - 细语呢喃
No comments:
Post a Comment