【leetcode】Best Time to Buy and Sell Stock II
来源:互联网 发布:php在线客服系统源码 编辑:程序博客网 时间:2024/06/06 04:56
问题:股票交易,交易的次数不限,但是要求在购买新的股票前,必须将旧的股票卖出,即同一时间,最多只能持有一只股票。要求在给定的交易价格序列中,计算出最大的收益。
分析:
保证利润最大,就要求在局部的价格波动中,能在低价买进,高价卖出,也就是说,找个价格走势的递增区间,并且这里可以交易多次,所以可以找到多个价格走势的递增区间,所有区间的收益的和就是最大的利润。
再看下不完全是递增区间的
通过这两种情况,我们得知,再计算的时候,只要遍历价格序列,将差值为正的部分加起来就可以了。当然求取每个递增区间求个区间的差值和也是可以的,这里只是探讨下这二者间存在的潜在的关系。
class Solution {public: int maxProfit(vector<int> &prices) { int len = prices.size(); int res = 0; for(int i = 1; i < len ; ++i){ if(prices[i] - prices[i - 1] > 0) res += prices[i] - prices[i - 1]; } if(res < 0) res = 0; return res; }};
1 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
- iOS—类似Android 9 patch效果图片拉伸
- 史上最强的Vim 配置文件(修正版)
- Linux下ps命令详解
- 面试笔试问题:大数据量,海量数据 处理方法总结
- Zeroc Ice3.4.2的demo无法打开
- 【leetcode】Best Time to Buy and Sell Stock II
- 轻应用能否创造社交营销新商业价值
- 单桂华-大规模天文时空数据的可视化
- as3与node.js的socket通信
- 【VC++】如何最大化对话框
- C++之动态绑定和静态绑定
- C#字符串压缩&解压
- WinCE注册表--创建、打开、读写、关闭
- Emacs 键绑定的格局