[LeetCode] 121. Best Time to Buy and Sell Stock
来源:互联网 发布:linux网速测试工具 编辑:程序博客网 时间:2024/06/05 08:14
Say you have an array for which the ith 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.
class Solution {public: int maxProfit(vector<int>& prices) { const int n = prices.size(); if (n == 0) return 0; int MinPrice = prices[0], MaxProfit = 0; for (int i = 1; i < n; i++) { MaxProfit = max(MaxProfit, prices[i] - MinPrice); MinPrice = min(MinPrice, prices[i]); } return MaxProfit; }};
阅读全文
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
- SQL Group By分组的使用
- 守护进程简单实现
- 用Python做深度学习(五)
- a标签常用的点击事件方法
- 链表的指定位置输出
- [LeetCode] 121. Best Time to Buy and Sell Stock
- C#设置DataGridView某一具体单元格的内容居中显示
- SpringMVC整合MongoDB开发(上)
- linux 管道符号 | ,以及&& ||等等特殊符号、通配符
- 《Python数据分析与挖掘实战》上机实验2——航空公司客户价值分析
- sql server 的T-SQL 学习笔记(四)
- android的学习点滴——PackageInfo、ResolveInfo
- Oracle 取随机数
- pinpoint