zoukankan      html  css  js  c++  java
  • 149. 买卖股票的最佳时机(回顾)

    149. 买卖股票的最佳时机

    中文English

    假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

    样例

    样例1

    输入: [3, 2, 3, 1, 2]
    输出: 1
    说明:你可以在第三天买入,第四天卖出,利润是 2 - 1 = 1
    

    样例2

    输入: [1, 2, 3, 4, 5]
    输出: 4
    说明:你可以在第0天买入,第四天卖出,利润是 5 - 1 = 4
    

    样例3

    输入: [5, 4, 3, 2, 1]
    输出: 0
    说明:你可以不进行任何操作然后也得不到任何利润
    输入测试数据 (每行一个参数)如何理解测试数据?
    第一种写法:
    class Solution:
        """
        @param prices: Given an integer array
        @return: Maximum profit
        """
        def maxProfit(self, prices):
            # write your code here
            total = 0
            buy_price = 2**32#避免prices为空,如果prices=[],则返回0,下面循环不执行.否则buy_price替换为第一个
            for price in prices:
           #如果利润大于上一个的话,则替换,最终返回
    if price - buy_price > total: total = price - buy_price
           #如果出现更小的价格,则替换,但自始至终保持利润最大才会替换
    if buy_price > price: buy_price = price return total

     另一种写法:

    class Solution:
        """
        @param prices: Given an integer array
        @return: Maximum profit
        """
        def maxProfit(self, prices):
            # write your code here
            max_pro = 0 
            buy_price = prices[0]
            for price in prices:
                max_pro = max(max_pro,price-buy_price)
                buy_price = min(buy_price,price)
            return max_pro
  • 相关阅读:
    Android登入界面
    安卓第4周作业
    第13周作业
    5.28上机作业
    5.22作业
    数据返回值
    登录
    安卓
    安卓第四周
    安卓第四周
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12832878.html
Copyright © 2011-2022 走看看