zoukankan      html  css  js  c++  java
  • 121. 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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    Note that you cannot sell a stock before you buy one.

    最多只能买一只股票,使得收益最大。那就只需要维护一个从0到i当前股票最小值,然后和当前值做差得到当前最大收益,然后再和全局最大收益做max。

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            if len(prices) < 2:
                return 0
            ans = 0
            min_current = prices[0]
            for i in range(1, len(prices), 1):
                ans = max(ans, prices[i] - min_current)
                min_current = min(min_current, prices[i])
            return ans
  • 相关阅读:
    英雄大乱斗
    深浅拷贝(copy)
    myleecode
    代码量简单统计
    pandas 模块 05
    matplotlib 模块 07
    KVC 和KVO浅谈
    iOS开发中懒加载的使用和限制
    关于空白模板插件的使用
    UIImageC处理
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13254208.html
Copyright © 2011-2022 走看看