LeetCode Best Time to Buy and Sell Stock II
2016-04-09 20:59
435 查看
LeetCode解题之Best Time to Buy and Sell Stock II
原题
给定每天的股票价格,如果允许进行多次交易,即可以多次买入和卖出,但手中最多只能持有一支股票,在再次买入的时候必须将之前的股票卖出,求能获取的最大利润。注意点:
无
例子:
输入: prices = [2, 4, 6, 1, 3, 8, 3]
输出: 11([2,6]、[1,8]是两次进行买入卖出的时机)
解题思路
可以进行多次交易的话,为了获取最多的利润,应该在每一段价格上升的区间的开头买入,末尾卖出。从前往后遍历数组,如果价格下跌,则在前一天卖出,在下跌的那天再次买入。不要忘记最后的上升段之后没有下跌的情况,要额外加上。AC源码
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 low = high = prices[0] profit = 0 for i in range(1, len(prices)): if prices[i] >= prices[i - 1]: high = prices[i] else: profit += high - low low = high = prices[i] profit += high - low return profit if __name__ == "__main__": assert Solution().maxProfit([2, 4, 6, 1, 3, 8, 3]) == 11
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法