Leetcode-Best Time to Buy and Sell Stock-Python
来源:互联网 发布:搜狐证券软件 编辑:程序博客网 时间:2024/06/10 14:21
Best Time to Buy and Sell Stock
买卖股票的最佳时机,返回最大收益。
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.
Description
解题思路:
依次遍历整个数组,利用minprice这个变量来保存每个元素之前的最低价格,并计算出在该元素卖出时能够带来的最大收益,最后将每个元素卖出时得到的最大收益进行比较即得到整个系统的最大收益。
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ maxprofit = 0 minprice = float('inf') for price in prices: minprice = min(minprice, price) profit = price - minprice maxprofit = max(maxprofit, profit) return maxprofit
tip:
Python中可以用如下方式表示正负无穷:float(“inf”), float(“-inf”)
阅读全文
0 0
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode] [Python] [DP] Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock III Leetcode Python
- [leetcode: Python] 121. Best Time to Buy and Sell Stock
- Leetcode-Best Time to Buy and Sell Stock-Python
- 【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]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
- hdu 2187
- 美团点评2017年秋招笔试题 改考卷
- (转)这是券商对金融科技最看重的一年!
- 懒加载的原理及实现
- 使用TensorFlow Object Detection API进行图像物体检测
- Leetcode-Best Time to Buy and Sell Stock-Python
- Subsequence Count 2017ccpc网络赛 1006 dp+线段树维护矩阵
- 成员初始化与final
- Java配置环境以及Editplus运行程序方法及问题
- 吴恩达深度学习入门学习笔记之神经网络和深度学习(第二周:神经网络基础)
- SPI专题(二)——STM32驱动FLASH(W25Q64)
- jpa学习笔记——3
- (转)“版本上线延时”问题与对策的探讨
- jenkins找不到Build when a change is pushed to GitHub