LeetCode:Best Time to Buy and Sell Stock
来源:互联网 发布:get it style 综艺 编辑:程序博客网 时间:2024/06/15 15:34
描述
Say you have an array for which the i-th element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction(ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
分析
解法一:使用贪心策略,分别找到价格最低和最高的一天,低进高出,注意最低的一天要在最高的一天之前。时间复杂度为O(n), 空间复杂度为O(1).
代码如下
class Solution {public: int maxProfit(vector<int> &prices) { if(prices.size() < 2) return 0; int profit = 0; int cur_min = prices[0]; for (int i = 1; i < prices.size(); i++) { profit = max(profit, prices[i] - cur_min); cur_min = min(cur_min, prices[i]); } return profit; }}
解法二:把原始价格序列变成差分序列,本题也可以看做是最大m子段和,m=1。
阅读全文
0 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- Scala入门到精通——第六节:类和对象(一)
- 营销费用预算管理的IT应用之路
- 开发者需要了解的WebKit
- 【spring Mvc】SpringMVC 文件上传配置,多文件上传,使用的MultipartFile
- 内存泄漏和使用工作线程常见方式总结
- LeetCode:Best Time to Buy and Sell Stock
- Centos中vsftpd的安装和配置
- 基于网管针对无线微波设备的管理实施方案
- UntiyShader之深度纹理
- session详细解析(是不是过期、失效时间)
- 【HTML】- HTML和CSS实现下拉菜单
- Socket编程
- c51串口通讯
- cookie 和session 的区别详解