[leetcode: Python]122. Best Time to Buy and Sell Stock 2
来源:互联网 发布:手机淘宝设置货到付款 编辑:程序博客网 时间:2024/06/17 06:39
题目:
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). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题意:
这道题的第一个版本是要求只能买卖一次。
第二个版本也就是本题,对买卖次数无要求,但是,必须再买下一只股票前,把手里的先卖掉。
方法一:性能49ms
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ profit = 0 for i in range(len(prices)-1): if prices[i] < prices[i+1]: profit += prices[i+1] - prices[i] return profit
方法二:性能39ms
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 p = 0 res = [] for i in range(1,len(prices)): if prices[i] > prices[i-1]: res.append(prices[i] - prices[i-1]) return sum(res) if res else 0
0 0
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode] [Python] [DP] Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock III Leetcode Python
- [leetcode: Python] 121. Best Time to Buy and Sell Stock
- Leetcode-Best Time to Buy and Sell Stock-Python
- [leetcode: Python]122. Best Time to Buy and Sell Stock 2
- LeetCode 122. Best Time to Buy and Sell Stock II
- [Leetcode] 122. Best Time to Buy and Sell Stock II
- [leetcode] 122.Best Time to Buy and Sell Stock II
- 【leetcode】122.Best Time to Buy and Sell Stock II
- 【LeetCode】122.Best Time to Buy and Sell Stock II
- [leetcode] 122. Best Time to Buy and Sell Stock II
- LeetCode #122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II LeetCode
- [LeetCode]122. Best Time to Buy and Sell Stock II
- Leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- LeetCode 122. Best Time to Buy and Sell Stock II
- 基于DragonBoard 410c的智能门铃系列一之系统总构架
- ubuntu16.04安装cuda8和opencv3.2
- DES加密算法工具类
- Spring EmptyResultDataAccessException异常的源码分析和解决方法
- 带返回值的Python多线程方法
- [leetcode: Python]122. Best Time to Buy and Sell Stock 2
- 验证java执行了默认初始化
- MySQL 触发器
- udp发送结构体实例
- Servlet 编写过滤器
- MySQL 约束和修改数据表
- easyui combotree 实现勾选checkbox 同时选择所有子节点,取消父节点同时取消所有子节点
- 雷神战争中简单megetexture地图制作
- view添加手势与tableView的cell点击冲突问题