Dynamic Programming for Introduction to Algorithms (Python) [Elementary Algorithms—Dynamic Programming] [Likou Exercises] [Lanqiao Cup Exercises]


1. Climb the stairs (simple)

Question:
Suppose you are climbing stairs. It takes n steps before you can reach the top of the building.

You can climb 1 or 2 steps at a time. How many different ways can you get to the top of the building?

Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top of the building.
1st stage + 1st stage
2nd stage

Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top of the building.
Tier 1 + Tier 1 + Tier 1
Tier 1 + Tier 2
Tier 2 + Tier 1

Hint:
1 <= n <= 45

Source: LeetCode
Link: https://leetcode-cn.com/problems/climbing-stairs

Analysis:
We follow the general problem-solving steps of dynamic programming:

  1. Define an array and determine the meaning of its elements: In this question, we can define a one-dimensional array to store how many ways to move to the current position.
  2. Find out the relationship between the elements of the array and determine the relationship formula: From the question, we can see that there are two ways to walk the stairs, 1 step and 2 steps, so there are two possibilities to reach the current position, from the i - 1 grid or the i - 2 Grid jumped up. That is, the number of moves to reach the current grid is equal to the moves of the previous grid plus the moves of the previous two grids. That is, dp[i] = dp[i - 1] + dp[i - 2]
  3. Determine the initial value. The initial value of this question is well determined dp[1] = 1, dp[2] = 2

code:

class Solution:
    def climbStairs(self, n: int) -> int:
        dp = [i for i in range(n + 1)]
        for i in range(4,n + 1):
            dp[i] = dp[i - 1] + dp[i - 2]
        return dp[n]

2. The best time to buy and sell stocks (simple)

Topic:
Given an array prices, its i-th element prices[i] represents the price of a given stock on the i-th day.

You can only choose to buy the stock on one day and sell it on a different day in the future. Design an algorithm to calculate the maximum profit you can make.

Returns the maximum profit you can make from this trade. If you can't make any profit, return 0.

Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (stock price = 1), buy on day 5 (stock price = 6) Sell, maximum profit = 6-1 = 5.
Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price; at the same time, you cannot sell the stock before buying.

Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no trade is completed, so the maximum profit is 0.

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

Source: LeetCode
Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

Analysis:
I did not use the dynamic programming conventional solution of the first question for this question, but it also includes the idea of ​​dynamic programming in it. Traverse prices, get the minimum value of the stock on the day as the purchase value, and the price of the day as the selling value, find the profit of the day, and compare it with the maximum profit of the previous time, and keep the larger one. At the end of the cycle, just output the profit.

code:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        a = float('inf')
        b = float('-inf')
        for i in range(n):
            a = min(a,prices[i])
            b = max(b,prices[i] - a)
        return b

3. Maximum subsequence sum (simple)

Title:
Given an integer array nums, please find a continuous sub-array with the maximum sum (the sub-array contains at least one element), and return its maximum sum.

A subarray is a contiguous part of an array.

Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: Sum of consecutive subarrays [4,-1,2,1] Maximum, is 6.

Example 2:
Input: nums = [1]
Output: 1

Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23

Source: LeetCode
Link: https://leetcode-cn.com/problems/maximum-subarray

Analysis:
This is also a relatively simple question. We can define two values ​​ans = nums[0], temp= 0, one records the maximum sum, and the other records the current sum. The final result can be obtained by traversing the array.

code:

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        n = len(nums)
        ans,temp = nums[0],0
        for i in range(n):
            temp = max(temp + nums[i], nums[i])
            ans = max(ans,temp)
        return ans

4. Robbery (medium)

Topic:
You are a professional thief planning to rob houses along the street. There is a certain amount of cash hidden in each room. The only restrictive factor that affects your theft is that the adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are broken into by thieves on the same night, the system will automatically call the police. .

Given an array of non-negative integers representing the amount stored in each house, calculate the maximum amount you can steal in one night without triggering the alarm.

Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: Steal house number 1 (amount = 1), then steal house number 3 (amount = 3).
Maximum amount stolen = 1 + 3 = 4.

Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: Steal house No. 1 (amount = 2), steal house No. 3 (amount = 9), then steal house No. 5 (amount = 1 ).
Maximum amount stolen = 2 + 9 + 1 = 12.

提示:
1 <= nums.length <= 100
0 <= nums[i] <= 400

Source: LeetCode
Link: https://leetcode-cn.com/problems/house-robber
Copyright belongs to LeetCode Network. For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate the source.
Analysis:
General problem-solving steps of dynamic programming:

  1. Define an array and determine the meaning of its elements: In this question, we can define a one-dimensional array to store the maximum amount that can be stolen in the i-th room.
  2. Find the relationship between the elements of the array and determine the relational expression: From the question, the room cannot be stolen continuously, so we can judge "the sum of the maximum amount obtained when arriving at room i - 2 plus the amount of the current room i" With the size of "reaching the maximum amount stolen in room i - 1", keep the larger one, and finally output the last value of the array. That is, dp[i] = max(dp[i - 2] + nums[i],dp[i - 1])
  3. Determine the initial value. dp[0],dp[1] = nums[0],max(nums[0],nums[1])

code:

class Solution:
    def rob(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            return nums[0]
        dp = [0 for i in range(n)]
        dp[0],dp[1] = nums[0],max(nums[0],nums[1])
        for i in range(2,n):
            dp[i] = max(dp[i - 2] + nums[i],dp[i - 1])
        return dp[n - 1]

Guess you like

Origin blog.csdn.net/youngwyj/article/details/122925892