121. Best Time to Buy and Sell Stock -Easy
来源:互联网 发布:淘宝卖农副产品挣钱吗 编辑:程序博客网 时间:2024/06/05 21:56
Question
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.
假设给你一个数组,其中第i个元素代表第i天的股票价格。如果你仅被允许最多一次交易(买一次以及卖一次股票)。现在要求你设计出一个算法找到使利益最大的交易
Example
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)
Solution
动态规划解。我们需要维护一个最大利益的值max_profit和最低买入点low_buy,我们每遇到一个更低的买入点,我们都需要更新low_buy,而对于任意一个买入点,接下来每一天卖出得到有可能得到的利益我们都需要更新max_profit。比如[7, 2, 3, 1, 4],当遇到2,low_buy=2,遇到了3,我们得到当前max_profit=1,遇到了1,low_buy=2,遇到了4,max_profit=3,所以最终返回3
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) == 0: return 0 max_profit = 0 low_buy = prices[0] for index_p, p in enumerate(prices): # 如果当前股票价格小于之前的最低价格,则更新最低价格 if p < low_buy: low_buy = p # 更新最大收益 elif p - low_buy > max_profit: max_profit = p - low_buy return max_profit
0 0
- 121. Best Time to Buy and Sell Stock [easy] (Python)
- 121. Best Time to Buy and Sell Stock -Easy
- Easy 121题 Best Time to Buy and Sell Stock
- [Easy]Best Time to Buy and Sell Stock
- Easy : 122. Best Time to Buy and Sell Stock II
- 【Leetcode-Easy-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
- 文件输入输出&文件模式
- filter笔记(2)
- js实现排序算法(冒泡、选择、插入、二分插入、快速、希尔)
- qt mingw版本编译报错:incorrect register `%rax' used with `l' suffix
- 分类和聚类的区别
- 121. Best Time to Buy and Sell Stock -Easy
- spring boot mybatis 简单整合使用
- 10马踏棋盘之中国象棋
- Codeforces Round #397(Div. 1 + Div. 2 combined)B. Code obfuscation【水题】
- 【bzoj1036】树的统计 树链剖分/LCT
- Eclipse解决“Archive for required library: ...”错误
- 程序员必备基础知识:通信协议——Http、TCP、UDP
- 内联函数和宏定义的区别
- Android开发中Animation动画详解