leetcode Best Time to Buy and Sell Stock II
来源:互联网 发布:怎样做淘宝优惠群 编辑:程序博客网 时间:2024/06/06 02:52
分析:题目的意思是整个过程中只能买一只股票然后卖出,也可以不买股票。也就是我们要找到一对最低价和最高价,最低价在最高价前面,以最低价买入股票,以最低价卖出股票。可以买卖多次股票,但是不能连续买股票,也就是说手上最多只能有一只股票(注意:可以在同一天卖出手上的股票然后再买进)
算法复杂度:O(n)
思路:
找到所有递增区间的利润。按照股票差价构成新数组 prices[1]-prices[0], prices[2]-prices[1], prices[3]-prices[2], ..., prices[n-1]-prices[n-2]。把数组中所有差价为正的值加起来就是最大利润了。因为只有递增区间内的差价是正数,并且同一递增区间内所有差价之和 = 区间最大价格 - 区间最小价格
int maxProfit(vector<int> &prices){ int n = prices.size(); if(n<=1) return 0; int profit=0; //所有差值为正的相加 for(int i=1; i<n; i++){ int dif = prices[i]-prices[i-1]; if(dif>0) { profit += dif; } } return profit; }
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
- codechef Open the Dragon Scroll bitset容器的运用
- 页面上插入视频播放器时,经常会遇到视频挡住js弹框的问题:
- 推荐几款不错的报表工具
- 关于EditText的inputType属性
- Oracle WebCenter 介绍
- leetcode Best Time to Buy and Sell Stock II
- [2013山东ACM省赛] Contest Print Server (模拟)
- 答读者问(2):有关研究生论文及实习等问题
- 转贴:svnserve作为Windows服务
- OWASP WebGoat---安全测试学习笔记(五)---缓冲区溢出
- neighbour table overflow 问题解决
- eclipse内存溢出:OutOfMemoryError:Java heap space
- php 字符串函数详解
- 最大子序列和问题