leetcode @python 123. Best Time to Buy and Sell Stock III
2016-04-01 19:00
761 查看
题目链接
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/题目原文
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 at most two transactions.
题目大意
给定不同交易日的股票价格,只能做两次交易,求最大的收益解题思路
First assume that we have no money, so buy1 means that we have to borrow money from others, we want to borrow less so that we have to make our balance as max as we can(because this is negative).
sell1 means we decide to sell the stock, after selling it we have price[i] money and we have to give back the money we owed, so we have price[i] - |buy1| = prices[i ] + buy1, we want to make this max.
buy2 means we want to buy another stock, we already have sell1 money, so after buying stock2 we have buy2 = sell1 - price[i] money left, we want more money left, so we make it max
sell2 means we want to sell stock2, we can have price[i] money after selling it, and we have buy2 money left before, so sell2 = buy2 + prices[i], we make this max.
So sell2 is the most money we can have.
代码
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ s1, s2 = 0, 0 b1, b2 = -2147483648, -2147483648 for i in range(len(prices)): b1 = max(b1, -prices[i]) s1 = max(s1, b1 + prices[i]) b2 = max(b2, s1 - prices[i]) s2 = max(s2, b2 + prices[i]) return s2
相关文章推荐
- leetcode @python 122. Best Time to Buy and Sell Stock II
- leetcode @python 121. Best Time to Buy and Sell Stock
- 学习python单元测试框架nose之---05nose的tools使用
- python自动化配置脚本分析
- Python实现 zip解压缩到指定目录
- 学习python单元测试框架nose之---04nose的html测试报告输出
- Python使用XPATH解析特定结构XML文件速度提升方法
- 学习python单元测试框架nose之---03nose的xml测试报告输出
- 使用python的zabbix_api模块
- 学习python单元测试框架nose之---02nose多进程并行测试
- IP地址地理位置接口(python版)
- 学习python单元测试框架nose之---01nose框架初探
- python 多线程
- A Byte of Python 笔记(9) 面向对象编程
- [Java学习] Iterator, foreach, generics and callback in Java, C# and Python
- Python kmean
- Install Python 3.5.1 on Windows
- python文件和目录操作方法大全(含实例)
- python rpyc的应用 ——聊天的功能(带认证)
- Python开发测试工具(一)—Monkey