122. Best Time to Buy and Sell Stock II
来源:互联网 发布:到培训班学淘宝靠谱吗 编辑:程序博客网 时间:2024/06/11 04:36
这道题是买卖股票的改进,由只能一次买卖操作改成可以多次买卖,问最大收益是多少。
这道题其实很简单,贪心即可,遍历数组,如果这一天价格大于昨天价格,那么就昨天买进今天卖出。一开始不敢用贪心,因为不知道有没有什么情况是今天买进,明天价格虽然高于今天,但是不是明天卖出能获得最大收益的情况。但是看了别人的分析之后发现多虑了。因为如果今天买进,明天价格虽然高于今天但是明天不卖出,而是等到后面某一天卖出,那肯定是因为那一天价格最高,但其实对于一个递增序列来说,比如1,2,4,99这个序列,第一天买进,99这一天卖出的话获益98,这和1买进2卖出4买进99卖出所获得的收益是一样的,都是最大的。这个题也是一样,只要是递增序列,就大胆的用第二天的前减去昨天的小的钱就可以。
class Solution {public: int maxProfit(vector<int>& prices) { int res = 0; for(int i = 1; i < prices.size(); ++i){ if(prices[i] > prices[i-1]) res += prices[i] - prices[i-1]; } return res; }};
阅读全文
0 0
- 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] 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】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
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 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 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- Oracle数据备份与恢复
- 大数据(二十五)Hive【Hive 函数 及其 自定义函数】
- AOSP 安卓源码7.1编译-真机运行
- Android 自定义view综合实战
- 《疯狂的程序员》有感
- 122. Best Time to Buy and Sell Stock II
- JSP(7)—EL和JSTL
- C
- C#语言笔记-1
- android MVVM开发框架——(4)DataBinding绑定view自定义属性
- javascript的封装jQuery
- 数据结构专题——线性表之单链表及其Java实现
- Freertos消息队列接收源码xQueueGenericReceive分析
- 作业2