leetcode122题解
来源:互联网 发布:无锡关键词优化 编辑:程序博客网 时间:2024/05/22 00:41
leetcode 122. Best Time to Buy and Sell Stock II
题目
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题目意思就是:给定一个数组,第i个值代表的就是第i天的股票价格。在整个周期里面,可以做多次买入或卖出操作,但要求在买入之前,要先卖出当前股票。
看到这道题时有点昏,因为没给example,描述也不是很清晰,这里给几个例子,方便理解。
[1,2,3] 输出:2 [2,1] 输出:0
解题思路
这道题看到之后,我们先分析一个具体的输入——输入:[1,2,3,4]
显然,第一天买入,最后一天卖出,收益最大为3.但考虑这样一种操作,遇到高的我就卖出,并买入。第一天买入,第二天卖出加买入……这样得到的结果也是3。
这其实就是一种贪心算法,下面是两种思路,核心都和刚刚说的类似。
代码1:循环该数组,若发现当前的值大于买入价格,则说明此时就有利润了,卖出并将当前值设为买入价格;若发现当前值小于买入价格,则把当前值设为最小买入价格。
代码2:leetcode上的大神的思路,就是比较相邻两值,后者比前者大就说明有利润,累加进总利润即可
AC代码如下
代码1:
//局部最优之和等于最大利润class Solution {public:int maxProfit(vector<int>& prices) {if(prices.size()==0)return 0;int sumprofit=0;int minbuyprice=prices[0];for(int i=1;i<prices.size();i++){ if(prices[i]>minbuyprice) sumprofit+=prices[i]-minbuyprice; minbuyprice=prices[i];}return sumprofit;}};
代码2:
class Solution {public:int maxProfit(vector<int>& prices) {int sumprofit=0;for(int i=1;i<prices.size();i++){ sumprofit+=max(prices[i]-prices[i-1],0); }return sumprofit;}};
总结
leetcode上easy难度,也是Best Time to Buy and Sell Stock这个系列里面的第二题。
关于贪心算法,在csdn上看到一篇不错的文章。
http://blog.csdn.net/qq_32400847/article/details/51336300
- leetcode122题解
- leetcode122
- leetcode122
- LeetCode122. Best Time to Buy and Sell Stock II题解
- Leetcode122: 3Sum Closest
- 题解
- 题解
- 题解
- 题解
- 题解
- 题解
- 题解
- 题解
- 题解
- 题解
- 题解
- 题解~~~~
- 题解。。。。
- 浅谈大数据建模
- 读取数据库信息,使用QR码API批量生成二维码并下载到本地
- 在主方法中实现不同数据类型到字符串的转换
- BZOJ 2407 探险
- 沉浸式状态栏
- leetcode122题解
- 19. OP-TEE中TA与CA执行流程详解-------软件架构篇
- 装饰模式(Decorator)
- N的N次方
- cooledit注册码
- 玩游戏也能破案?警察上班时间打游戏,只为让男孩开口!
- linux安装mysql nginx 设置 mysql apache开机启动
- Junit4中的测试注解
- 下列代码中,第几行的obj符合垃圾收集器的收集标准