zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第121题:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。 注意:你不能在买入股票前卖出股票。

    题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。  如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。  注意:你不能在买入股票前卖出股票。
    思路:动态规划(最佳),还可以用暴力
    在某教育科技公司面试时遇到过。
    程序1:动态规划
    class Solution:
        def maxProfit(self, prices: List[int]) -> int:
            length = len(prices)
            if length <= 1:
                return 0
            buy = prices[0]
            auxiliary = [0] * length
            for index in range(1, length):
                auxiliary[index] = max(auxiliary[index - 1], prices[index] - buy)
                buy = min(buy, prices[index])
            result = max(auxiliary)
            return result
    程序2:暴力
    class Solution:
        def maxProfit(self, prices: List[int]) -> int:
            length = len(prices)
            if length <= 1:
                return 0
            if length == 2:
                if prices[0] >= prices[1]:
                    return 0
                else:
                    return prices[1] - prices[0]
            #Find the buy point
            index1 = 1
            auxiliary_buy = []
            auxiliary_buy.append(prices[1])
            auxiliary_sell = []
            auxiliary_sell.append(prices[length - 1])
            while index1 < length:
                if prices[index1] < prices[index1 - 1]:
                    auxiliary_buy.append(prices[index1])
                    buy = min(auxiliary_buy)
                    #Find the sell point
                    auxiliary_sell.append(max(prices[index1 : ]))
                    sell = max(auxiliary_sell)
                    result = sell - buy 
                    if result <= 0:
                        return 0
                        break
                index1 += 1
            return result
                
  • 相关阅读:
    cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
    “校长风暴”来袭,《诺亚幻想》不删档数据惊艳
    地形植被编辑器
    游戏记录
    2016乐高迷们不能错过的十大乐高模型
    UI相关教程:HUD、UMG和Widget
    [UE4]C++中SpawnActor用法(动态创建Actor)
    [UE4][Canvas]用C++代码绘制血条(HealthBar)
    [UE4]C++代码实现播放粒子特效
    [UE4]C++实现动态加载的问题:LoadClass<T>()和LoadObject<T>() 及 静态加载问题:ConstructorHelpers::FClassFinder()和FObjectFinder()
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12743136.html
Copyright © 2011-2022 走看看