Last active
March 7, 2016 02:52
-
-
Save mebusw/8a289cad7b53247a86b7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! encoding=utf8 | |
import unittest | |
def maxProfit(prices): | |
if not prices: | |
return 0 | |
currBuy = -prices[0] #表示当天最终未持股的情况下,当天结束后的累计最大利润 | |
currSell = 0 #表示当天最终持股的情况下,当天结束后的累计最大利润 | |
prevSell = 0 | |
ops = ['buy'] #考虑初始情况 | |
op_of_today = '' | |
for i in xrange(1, len(prices)): | |
temp = currSell | |
if currBuy + prices[i] > currSell: | |
op_of_today = 'sell' | |
currSell = max(currSell, currBuy + prices[i]) | |
if i >= 2: | |
if prevSell - prices[i] > currBuy: | |
op_of_today = 'buy' | |
currBuy = max(currBuy, prevSell - prices[i]) | |
else: | |
if -prices[i] > currBuy: | |
op_of_today = 'buy' | |
currBuy = max(currBuy, -prices[i]) | |
prevSell = temp | |
ops.append('cooldown' if ops[-1] == 'sell' else op_of_today) | |
return currSell, ops | |
class StockTest(unittest.TestCase): | |
def test_something(self): | |
self.assertEqual((3, ['buy', 'sell', 'cooldown', 'buy', 'sell']), maxProfit([1, 2, 3, 0, 2])) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment