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这个变量来保存每个元素之前的最低价格,并计算出在该元素卖出时能够带来的最大收益,最后将每个元素卖出时得到的最大收益进行比较即得到整个系统的最大收益。
1 | class Solution(object): |
tip:
Python中可以用如下方式表示正负无穷:float(“inf”), float(“-inf”)