[leetcode]Best Time to Buy and Sell Stock @ Python

原题地址:https://oj.leetcode.com/problems/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.

解题思路:扫描一遍数组,使用low来标记最低价位,如果有更低的价位,置换掉。

代码:

class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        if len(prices) <= 1: return 0
        low = prices[0]
        maxprofit = 0
        for i in range(len(prices)):
            if prices[i] < low: low = prices[i]
            maxprofit = max(maxprofit, prices[i] - low)
        return maxprofit
原文地址:https://www.cnblogs.com/zuoyuan/p/3765934.html