leetcode 122. Best Time to Buy and Sell Stock II-股票交易|贪心算法
来源:互联网 发布:iphonese怎么样知乎 编辑:程序博客网 时间:2024/06/01 12:30
原题链接:122. Best Time to Buy and Sell Stock II
【思路-Java、Python】
假设每天最多可以进行2次交易(一次买,一次卖)。那么用贪心算法,
①如果第 i 天相比第 i-1天有收益,那么就将收益放入到那么就在第 i-1 天买入股票(不管第 i-1 天是否持股,如果持股就卖出再买入),在第 i 天卖出。
②如果第 i 天相比第 i-1 天没有收益,那么就在第 i-1当天卖出。(相当于没有买也没有卖)
这样就可以将所有收益收入囊中,获得最大收益。但是题目规定,不可以进行多次交易。我们认真分析,发现多次交易其实是出现在①(因为②没有收益,那么我就不买入,也不卖出,当天不进行交易)。而①会出现多次交易是因为第 i-1 天持股,而持股的原因是因为第 i-1天相对于第 i-2天有收益,那么这个连续的收益过程实际上是可以合并为一次,即第 i-2天买入,第 i 天卖出。所以我们分析时当天多次交易这个矛盾,在实际操作中是可以化解的:
public class Solution { public int maxProfit(int[] prices) { if (prices.length < 2) return 0; int maxPro = 0, lastBuy = prices[0]; for (int i = 1; i < prices.length; i++) { if (prices[i] > lastBuy) maxPro += prices[i] - lastBuy; lastBuy = prices[i]; } return maxPro; }}198 / 198 test cases passed. Runtime: 2 ms Your runtime beats 15.31% of javasubmissions.
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+1] > prices[i]) : profit += prices[i+1] - prices[i]; return profit198 / 198 test cases passed. Runtime: 56 ms Your runtime beats 32.51% of pythonsubmissions.
1 0
- leetcode 122. Best Time to Buy and Sell Stock II-股票交易|贪心算法
- 122.leetcode Best Time to Buy and Sell Stock II(medium)[贪心算法 数组]
- [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-122:Best Time to Buy and Sell Stock II (多次股票交易最大利润)
- [C++]LeetCode: 77 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
- 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
- 灰度梯度共生矩阵纹理特征
- scala中val function
- android入门-Activity的四种启动模式详解
- Duilib教程-HelloDuilib及DuiDesigner的简单使用
- 我为什么不是清华的学生
- leetcode 122. Best Time to Buy and Sell Stock II-股票交易|贪心算法
- Linux文件属性
- JAVA多线程(一)基本概念和上下文切换性能损耗
- SD卡,SharedPreference以及Pull解析
- 【LeetCode】50. Pow(x, n)
- Spring实现AOP的4种方式(转)
- 第十三周项目三 分数类中的运算符重载 (1)
- OpenCV人脸检测
- eclipse容易卡死或者较慢的解决方案