121. Best Time to Buy and Sell Stock(第十一周)
来源:互联网 发布:手机图片恢复软件 编辑:程序博客网 时间:2024/06/07 02:22
Description
Best Time to Buy and Sell Stock - LeetCode
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.
Solution
这是一个简单的O(n)
算法问题,我们首先排除空的数组,让它直接等于0。
后由样例2我们知道最少的profit
为0,所以我们一开始设置profit
的值就应该是0。然后标记一个最少的值,我们称为min
,对于非空的数组,我们一开始把min
的值设置为prices[0]
的值,然后进行遍历,如果遇到比min
小的值就把这个值赋给min
,如果不是就将这个数和min
进行相减,得到的数值与profit
比较,如果比profit
大,那么就将这个值赋给profit
。
问题解决。
代码如下:
Source Code
submission
class Solution {public: int maxProfit(vector<int>& prices) { if (prices.empty()) { return 0; } int min = prices[0]; int profit = 0; for (int i = 1; i < prices.size(); i++) { if (prices[i] < min) { min = prices[i]; } else { if (prices[i] - min > profit) { profit = prices[i] - min; } } } return profit; }};
Comment
一个比较简单的题目,能用O(n)
时间复杂度解决。
阅读全文
0 0
- 121. Best Time to Buy and Sell Stock(第十一周)
- 121. Best Time to Buy and Sell Stock(贪心)
- 121. Best Time to Buy and Sell Stock ()
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Spark SQL 整合Hive的使用
- CentOS 安装python
- Linux之Redhat中搭建mysql数据库及数据库的管理
- hadoop SecondNamenode详解
- 两个线程,轮流有序执行的两种方法
- 121. Best Time to Buy and Sell Stock(第十一周)
- 1198 渊子赛马(贪心算法)
- C通用的字符串函数(_t)
- 实时获取微信聊天消息记录
- 创建你的第一个ThreeJs场景
- 跨平台开源项目Ngui【视图与布局系统】
- 网络流学习笔记(1)
- 第九次作业
- java反射回顾<二>