您的位置:首页 > 编程语言 > Python开发

Leetcode-Best Time to Buy and Sell Stock-Python

2017-08-31 22:17 369 查看

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”)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python algorithm