leetcode-Best Time to Buy and Sell Stock-121
来源:互联网 发布:单片机蜂鸣器音乐程序 编辑:程序博客网 时间:2024/05/17 08:42
a[i]代表第i天商品的价格,问如果我买入一次再卖出一次,能得到的最大利润。
直观的做法是二重循环,枚举第i天买入,然后枚举大于第i天卖出,计算利润更新最大值。
利用贪心思想可得线性做法:假设第i天买入,那么肯定选第i天以后商品价格最大的那天卖出,因此从后往前遍历,更新最大的价格,同时减去当前价格就是当天买入能得到的最大利润,只需遍历一遍。
class Solution {public: int maxProfit(vector<int>& prices) { int len=prices.size(); if(len==0||len==1) return 0; int mx=prices[len-1]; int ans=0; for(int i=len-2;i>=0;i--){ if(mx>prices[i]) ans=max(ans,mx-prices[i]); else mx=prices[i]; } return ans; }};
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: Best Time to Buy and Sell Stock [121]
- LeetCode 121 Best Time to Buy and Sell Stock
- [leetcode 121] Best Time to Buy and Sell Stock
- Leetcode NO.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 (Java)
- leetcode-121 Best Time to Buy and Sell Stock
- leetcode || 121、Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock - LeetCode 121
- 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]
- 设计模式 组合模式
- CSS (float,clear)
- lcd驱动
- mysql出现中文乱码或不能输入中文问题的Windows或Linux系统解决方法
- java笔记--day09--接口(三)类和接口的关系
- leetcode-Best Time to Buy and Sell Stock-121
- POJ 1198 Solitaire(bfs)
- 09. Yii 2.0 数据库交互 -读写分离
- How To Install Go 1.6 on Ubuntu 14.04
- keep on coding 8.26-3
- Android Camera架构分层及代码结构(MTK version)
- [387] First Unique Character in a String
- Android SDK Manager 更新代理配置
- 【BZOJ2337】XOR和路径,概率期望DP+高斯消元