Best Time to Buy and Sell Stock II -- LeetCode
来源:互联网 发布:一般淘宝代购是正品吗 编辑:程序博客网 时间:2024/06/18 13:40
原题链接: http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
这道题跟Best Time to Buy and Sell Stock类似,求最大利润。区别是这里可以交易无限多次(当然我们知道交易不会超过n-1次,也就是每天都进行先卖然后买)。既然交易次数没有限定,可以看出我们只要对于每次两天差价大于0的都进行交易,就可以得到最大利润。因此算法其实就是累加所有大于0的差价既可以了,非常简单。如此只需要一次扫描就可以了,时间复杂度是O(n),空间上只需要O(1)存一个累加结果即可。代码如下:
这道题跟Best Time to Buy and Sell Stock类似,求最大利润。区别是这里可以交易无限多次(当然我们知道交易不会超过n-1次,也就是每天都进行先卖然后买)。既然交易次数没有限定,可以看出我们只要对于每次两天差价大于0的都进行交易,就可以得到最大利润。因此算法其实就是累加所有大于0的差价既可以了,非常简单。如此只需要一次扫描就可以了,时间复杂度是O(n),空间上只需要O(1)存一个累加结果即可。代码如下:
public int maxProfit(int[] prices) { if(prices == null || prices.length==0) return 0; int res = 0; for(int i=0;i<prices.length-1;i++) { int diff = prices[i+1]-prices[i]; if(diff>0) res += diff; } return res;}这道题其实比Best Time to Buy and Sell Stock更加简单,只需要看透背后的模型就很OK了哈。
57 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
- ZOJ 1057 Undercut (格式问题)
- 富豪应多做慈善事业
- java谜题1:奇数性
- codeforces #199 C. Cupboard and Balloons 题解
- 08-remove @Override annotation错误
- Best Time to Buy and Sell Stock II -- LeetCode
- dll和exe的共享节------多进程共享dll/exe全局变量
- 火星坐标和正常坐标之间的转换
- 我们为什么而活
- Debian GUN/Linux Desktop grap语言配置 [大三四八九月实习]
- C++学习日记之对象作为数据成员
- 谈谈android反编译和防止反编译的方法
- SVN 文件已锁定解决方法
- JavaScript 全局函数