【LeetCode】121. Best Time to Buy and Sell Stock
来源:互联网 发布:码农 大数据 编辑:程序博客网 时间:2024/06/06 17:26
问题描述
股票交易。数组第i个元素表示第i天股票的价格,整个过程只能买一次和卖一次,设计一个算法寻找最大收益。
例1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
只能先买进才能卖出,所以最大收益为6-1=5,而不是7-1=6。
例2:
Input: [7, 6, 4, 3, 1]
Output: 0
贪心。其实就是找一个数组里面的最大差值j-i,保证i < j即可。
//但是这个方法两重循环,超时了!class Solution {public: int maxProfit(vector<int>& prices) { if(prices.size() == 0) return 0; int result=0; int temp=0; for(int i=0;i<prices.size()-1;i++){ for(int j=i+1;j<prices.size();j++){ temp=prices[j]-prices[i]; result=max(result,temp); } } return result; }};
Time Limit Exceeded:
Last executed input:
[10000,9999,9998,9997,9996,9995,9994,9993,9992,9991,9990,9989…….]
所以我们需要优化。
AC代码如下:
class Solution {public: int maxProfit(vector<int>& prices) { int result=0; //始终记录最大值 int temp=0; //记录当天的收益,若为负,则置0重新计算收益(此时最大值已经被result保存下来了) for(int i=1; i<prices.size(); i++){ temp += (prices[i]-prices[i-1]); if(temp<0){ temp=0; } result=max(result,temp); } return result; }};
阅读全文
0 0
- LeetCode 121. Best Time to Buy and Sell Stock
- [Leetcode] 121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock LeetCode
- [LeetCode]121. Best Time to Buy and Sell Stock
- Leetcode 121. Best Time to Buy and Sell Stock
- leetcode 121. Best Time to Buy and Sell Stock
- LeetCode 121. Best Time to Buy and Sell Stock
- LeetCode题解:121. Best Time to Buy and Sell Stock
- LeetCode *** 121. Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock
- #leetcode#121. Best Time to Buy and Sell Stock
- LeetCode 121. Best Time to Buy and Sell Stock
- 121.[Leetcode]Best Time to Buy and Sell Stock
- leetcode 121. Best Time to Buy and Sell Stock
- Leetcode 121. Best Time to Buy and Sell Stock
- C++ 随笔
- 前端基础
- linshi
- 学习Linux命令(41)
- CentOS系统中使用yum命令安装redis
- 【LeetCode】121. Best Time to Buy and Sell Stock
- 使用 matlab 心电数据捕获心率
- 微信js sdk invalid signature签名错误
- lintcode python 代码 141 x 的平方根
- jquery
- ubuntu 添加ppa源
- Hadoop集群安装配置教程_Hadoop2.6.0_Ubuntu/CentOS
- TCP定时器
- linux常用命令