栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

121.买卖股票的时机

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

121.买卖股票的时机

文章目录
      • 题目
      • 方法一:暴力解决
        • 思路
        • 代码
        • 运行结果
      • 方法二:固定一端
        • 思路
        • 代码
        • 运行结果
      • 方法三:使用动态规划
        • 思路
        • 代码
        • 运行结果

题目
'''
Description: 121.买卖股票的最佳时机
Autor: 365JHWZGo
Date: 2021-12-08 20:36:09
LastEditors: 365JHWZGo
LastEditTime: 2021-12-08 21:55:30
'''
方法一:暴力解决 思路

通过控制头指针和尾指针来寻找最大差值。

代码
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        maxProfit = 0
        for i in range(len(prices)):
            for j in range(i,len(prices)):
                if prices[j]-prices[i]>maxProfit:
                    maxProfit = prices[j]-prices[i]
        return maxProfit
运行结果

方法二:固定一端 思路

从思路一可以看出利润最大值之和当前来说最低买入和最高卖出有关,那么我们是不是可以确定一头,遍历另一头。

代码
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        #买入点
        buyPoint = prices[0]
        #最大利润
        maxProfit = 0
        #依次遍历卖出点,因为卖出点不能和买入点同一天,所以从第二天开始
        for i in range(1,len(prices)):
            sellPoint = prices[i]            
            if sellPoint-buyPoint>=0:
                maxProfit = max(sellPoint-buyPoint,maxProfit)   
                # 当当前买入点比以前确定的买入点低,则重新赋值    
                if buyPoint>prices[i]:
                    buyPoint = prices[i]
            else:
                buyPoint = sellPoint
        return maxProfit  
运行结果

方法三:使用动态规划 思路
        1.确定dp数组以及下标含义
            dp[i]代表第i天的最大收益
        2.确定递推公式
            dp[i]=max(prices[i]-prices[buyPoint],dp[i-1])
        3.初始化dp数组
            dp[0]=0
            第0天的最大收益为0
            dp数组全部初始化为0
        4.确定遍历顺序
            从前往后依次遍历
        5.举例推导
            EG:prices=[7,1,5,3,6,4]
            dp   [0, 0, 4, 4, 5, 5]
            5
代码
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        dp = [0]*len(prices)
        dp[0] = 0
        buyPoint = 0
        for i in range(1,len(prices)):
            if prices[i]-prices[buyPoint] <= 0:
                buyPoint = i
            dp[i] = max(prices[i]-prices[buyPoint],dp[i-1])
        # print(dp)
        return dp[-1]
运行结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/649322.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号