2018年6月1日 星期五

[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown

轉自LeetCode

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

Best Time to Buy and Sell Stock 的衍生題

想法如下
  • 用變數 profitAfterBuy 表示,在今天以前,最後一次動作是 buy 的情況下,能賺到的最大獲利
  • 用變數 profitAfterSell 表示,在今天以前,最後一次動作是 sell 的情況下,能賺到的最大獲利
  • 歷遍 prices,每個 price 都會有兩種選擇,要或不要(因為有 cooldown 的關係),將這兩種選擇的情況都考慮到 buy 和 sell
code 如下


Kotlin

沒有留言:

張貼留言