[Swift]LeetCode309. 最佳買賣股票時機含冷凍期 | Best Time to Buy and Sell Stock with Cooldown

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-fsepgmbs-kq.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Say you have an array for which the ith element is the price of a given stock on day i.git

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:github

  • 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]

給定一個整數數組,其中第 i 個元素表明了第 i 天的股票價格 。​數組

設計一個算法計算出最大利潤。在知足如下約束條件下,你能夠儘量地完成更多的交易(屢次買賣一支股票):微信

  • 你不能同時參與多筆交易(你必須在再次購買前出售掉以前的股票)。
  • 賣出股票後,你沒法在次日買入股票 (即冷凍期爲 1 天)。

示例:spa

輸入: [1,2,3,0,2]
輸出: 3 
解釋: 對應的交易狀態爲: [買入, 賣出, 冷凍期, 買入, 賣出]

16ms
 1 class Solution {
 2     func maxProfit(_ prices: [Int]) -> Int {
 3     if prices.count <= 1 {
 4          return 0 
 5     }
 6     var s0: Int = 0
 7     var s1: Int = -prices[0]
 8     var s2: Int = Int.min
 9     for i in 1 ..< prices.count {
10         let pre0 = s0
11         let pre1 = s1
12         let pre2 = s2
13         s0 = max(pre0, pre2)
14         s1 = max(pre0 - prices[i], pre1)
15         s2 = pre1 + prices[i]
16     }
17     return max(s0, s2)
18 }
19 }

28ms設計

 1 class Solution {
 2     func maxProfit(_ prices: [Int]) -> Int {
 3         var buy = Int.min, noOp = Int.min
 4         var coolDown = 0, sell = 0
 5         for  p in prices {
 6             noOp = max(noOp, buy)
 7             buy = coolDown - p
 8             coolDown = max(coolDown, sell)
 9             sell = noOp + p;
10         }
11         return max(coolDown, sell)
12     }
13 }
相關文章
相關標籤/搜索