动态规划示例题

1、 最大子序和

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例 1:

输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。

示例 2: 

输入:nums = [1]
输出:1

示例 3:

输入:nums = [0]
输出:0

示例 4:

输入:nums = [-1]
输出:-1

示例 5:

输入:nums = [-100000]
输出:-100000

方式一:动态规划

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        dp = [0] * len(nums)    # dp[i] 表示 nums 以 i-th 元素结尾的最大连续子数组之和

        # dp[i] = max(dp[i - 1] + nums[i], nums[i])    # nums 中以第 i 个元素结尾的最大连续子数组之和为: “以第 i-1 个元素结尾的最大连续子数组之和加上 nums[i]” 与 “nums[i]” 中的较大值

        dp[0] = nums[0]
        
        for i in range(1, len(nums)):
            dp[i] = max(dp[i - 1] + nums[i], nums[i])
        
        return max(dp)

方式二:也是基于动态规划的思想,只是不再生成额外的数组,而是把其中的临时变量保存下来。

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        res_max = tmp_max = nums[0]    # res_max 记录历史最大值,也是最后要返回的结果; tmp_max 保存的是nums 在当前索引时的最大值。

        for i in range(1, len(nums)):
            tmp_max = max(tmp_max + nums[i], nums[i])    # “nums 在 i-1 索引时的最大值加上 nums 在 i 索引时的值”,与 “nums 在 i 索引时的值”中较大者,即为当前nums在 i 索引时的最大值
            res_max = max(res_max, tmp_max)       # 当前最大值和历史最大值中取较大者,即为有史以来的最大值

        return res_max

题目链接: https://leetcode-cn.com/problems/maximum-subarray/

 

2、买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

 

示例 1:

输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。


示例 2:

输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
 

提示:

1 <= prices.length <= 105
0 <= prices[i] <= 104

 方式一:动态规划

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)

        if n < 2: return 0

        dp = [0] * n    # dp[i] 表示 到第 i 天时所能获得的最大利润
        min_price = prices[0]

        for i in range(1, n):
            min_price = min(min_price, prices[i])
            dp[i] = max(dp[i - 1], prices[i] - min_price)   # 第 i 天所能得到的最大利润为:“到前一天所能得到的最大利润”和“今天所能获得的最大利润”中的较大值

        return dp[-1]

方式二:也是基于动态规划,但也是不再生成新的数组,而是保存临时的变量。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        if n < 2: return 0

        min_price = prices[0]    # 保存有史以来的最小价格
        max_profit = 0              # 保存有史以来的最大利润

        for i in range(1, n):
            min_price = min(min_price, prices[i])     # 把以前的最小值和当前值比较,取出较小值

            max_profit = max(max_profit, prices[i] - min_price)      # 把以前的最大利润和当前的利润比较,取出较大值

        return max_profit

题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

 

posted @ 2021-06-13 01:57  neozheng  阅读(50)  评论(0编辑  收藏  举报