Code Caprice Training Camp day49| 121. The best time to buy and sell stocks 122. The best time to buy and sell stocks II

@TOC


foreword

Code Random Record Algorithm Training Camp day49


1. Leetcode 121. The best time to buy and sell stocks

1. 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), sell on day 5 (stock price = 6), 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 trades are completed, so the maximum profit is 0.

hint:

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

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

2. Problem-solving ideas

Method 2: One time traversal

algorithm

Suppose the given array is: [7, 1, 5, 3, 6, 4]

If we plot the numbers in the given array on the graph, we will get:

Profit Graph

Let's pretend we are buying stocks. Over time, every day we have the choice to sell our stock or not. So, assuming that on the i-th day, if we want to sell the stock today, how much money can we make?

Obviously, if we were actually buying or selling stocks, we would be thinking: If only I were buying stocks at all-time lows! Great, in the title, we only need to use a variable to record a historical minimum price minprice, and we can assume that our stocks were bought on that day. Then the profit we can get from selling the stock on day i is prices[i] - minprice.

Therefore, we only need to traverse the price array once, record the lowest point in history, and then consider such a question every day: If I bought at the lowest point in history, how much money can I make by selling today? When all the days are considered, we have the best answer.

3. Code implementation

```java public class Solution { public int maxProfit(int prices[]) { int minprice = Integer.MAX_VALUE; int maxprofit = 0; for (int i = 0; i < prices.length; i++) { if (prices[i] < minprice) { minprice = prices[i]; } else if (prices[i] - minprice > maxprofit) { maxprofit = prices[i] - minprice; } } return maxprofit; } }

```

2. Leetcode 122. The best time to buy and sell stocks II

1. Topic

You are given an integer array prices, where prices[i] represents the price of a certain stock on day i.

On each day, you can decide whether to buy and/or sell stocks. You can hold no more than one share of stock at any one time. You can also buy first and then sell on the same day.

Return the maximum profit you can make.

Example 1:

Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (stock price = 1), sell on day 3 (stock price = 5) Out, this transaction can make profit = 5 - 1 = 4. Then, buy on the 4th day (stock price = 3) and sell on the 5th day (stock price = 6), this transaction can make profit = 6 - 3 = 3. The total profit is 4 + 3 = 7.

Example 2:

Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (stock price = 1), sell on day 5 (stock price = 5), Profit = 5 - 1 = 4 for this trade. The total profit is 4.

Example 3:

Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, the transaction cannot obtain a positive profit, so the maximum profit can be obtained by not participating in the transaction, and the maximum profit is 0.

hint:

1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104

2. Problem-solving ideas

Method 1: Dynamic Programming

Considering that "you cannot participate in multiple transactions at the same time", after the end of each transaction, there may only be one stock or no stock in hand.

Define the state dp[i][0]dp[i][0] to represent the maximum profit without stocks in hand after the transaction on the ii day, and dp[i][1]dp[i][1] to represent the transaction on the ii day After the end, the maximum profit of holding a stock in hand (ii starts from 00).

Consider the transfer equation of dp[i][0]dp[i][0], if there is no stock in hand after the transaction on this day, then the possible transfer state is that there is no stock in the previous day, that is, dp[i−1][ 0]dp[i−1][0], or hold a stock at the end of the previous day, that is, dp[i−1][1]dp[i−1][1], at this time we want Sell ​​it for a price[i]prices[i] profit. Therefore, in order to maximize the revenue, we formulate the following transfer equation:

dp[i][0]=max⁡{dp[i−1][0],dp[i−1][1]+prices[i]}dp[i][0]=max{dp[i−1][0],dp[i−1][1]+prices[i]}

Consider dp[i][1]dp[i][1] again, and consider the transfer state in the same way, then the possible transfer state is that you have already held a stock the day before, that is, dp[i−1][1] dp[i−1][1], or there is no stock at the end of the previous day, that is, dp[i−1][0]dp[i−1][0], at this time we need to buy it and reduce prices[i] returns on prices[i]. The transfer equation can be listed as follows:

dp[i][1]=max⁡{dp[i−1][1],dp[i−1][0]−prices[i]}dp[i][1]=max{dp[i−1][1],dp[i−1][0]−prices[i]}

For the initial state, according to the state definition, we can know that dp[0][0]=0dp[0][0]=0, dp[0][1]=−prices[0]dp[ 0][1]=−prices[0].

Therefore, we only need to calculate the states sequentially from front to back. Since all transactions are completed, the income of holding stocks must be lower than that of not holding stocks, so at this time the income of dp[n−1][0]dp[n−1][0] must be greater than dp[n −1][1]dp[n−1][1], the final answer is dp[n−1][0]dp[n−1][0].

3. Code implementation

```java class Solution { public int maxProfit(int[] prices) { int n = prices.length; int[][] dp = new int[n][2]; dp[0][0] = 0; dp[0][1] = -prices[0]; for (int i = 1; i < n; ++i) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]); dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]); } return dp[n - 1][0]; } }

```

Guess you like

Origin blog.csdn.net/HHX_01/article/details/131285442