【leetcode】Best Time to Buy and Sell Stock II
来源:互联网 发布:分类信息群发软件 编辑:程序博客网 时间:2024/04/29 10:16
1.题目
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).
2. 分析
从价格表的极小点买入,从价格表的极大点卖出,即可获得最大利润。
3.代码
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) < 2: return 0 total = 0 buy = prices[0] sell = 0 cond_buy = True; for i in range(1,len(prices)): if( cond_buy): if(prices[i] <= prices[i-1]): buy = prices[i] else: cond_buy = False; sell = prices[i]; else: if(prices[i] >= prices[i-1]): sell = prices[i]; else: total += sell - buy; cond_buy = True; buy = prices[i] if (not cond_buy): total += sell - buy; return total
0 0
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- [Leetcode]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- LeetCode-Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock II
- Hibernate HQL 一对多查询
- 右值引用
- 程序设计基石与实践系列之C中的继承和多态
- JAVA爬虫Nutch、WebCollector的正则约束
- 网络管理Network
- 【leetcode】Best Time to Buy and Sell Stock II
- Anaconda python各模块简介
- HDU 1116 Play on Words(欧拉路径(有向图)+并查集)
- linux中对象文件的符号表symbols查看工具nm简介
- 程序设计基石与实践系列之编写高效的C程序与C代码优化
- 快速幂取模算法
- Java中读取图片和配置文件的写法
- SCU 3082 windy's cake II(容斥)
- Java中堆内存和栈内存详解