Leetcode 2020/12/07 Check in Offer 63. The maximum profit of stocks +122. The best time to buy and sell stocks II + 123. The best time to buy and sell stocks III

Source: LeetCode Link: https://leetcode-cn.com/problems/score-after-flipping-matrix
Statement: If I violate anyone’s rights, please contact me and I will delete it.
Welcome experts to spray I

Sword refers to Offer 63. The maximum profit of the stock

https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/

Assuming that the price of a certain stock is stored in an array in chronological order, what is the maximum profit that can be obtained from buying and selling the stock at one time?

Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on the 2nd day (stock price = 1), and on the 5th day (stock price = 6) Sell, the 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.

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

Here is a one-time sale, so buy at the lowest point and sell at the highest point after the lowest point:

    public int maxProfit (int[] prices) {
    
     
        if(prices==null || prices.length==0)return 0;
        int min = prices[0];
        int max = -1;
        // min记录最小的价钱,就是买入点
        //max记录最大的价钱,就是卖出点
        //因为min,max,都是在i变化时,都要更新的,就保证了max的点在min上或者在之后
        for(int p:prices){
    
    
            min = Math.min(min, p);
            max = Math.max(max, p-min);
        }
        return max;
    }
122. The Best Time to Buy and Sell Stocks II

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

Given an array, its i-th element is the price of a given stock on the i-th day.
Design an algorithm to calculate the maximum profit you can get. You can complete as many transactions as possible (buying and selling a stock multiple times).
Note: You cannot participate in multiple transactions at the same time (you must sell the previous stocks before buying again).

Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on the 2nd day (stock price = 1), and on the 3rd day (stock price = 5) Sell, this exchange can make a profit = 5-1 = 4.
Then, buy on the 4th day (stock price = 3), and sell on the 5th day (stock price = 6). The exchange can make a profit = 6-3 = 3.

Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on the 1st day (stock price = 1), and sell on the 5th day (stock price = 5) , This exchange can make a profit = 5-1 = 4.
Note that you cannot buy stocks one after another on the first and second days and then sell them later.
Because this is involved in multiple transactions at the same time, you must sell the previous stocks before buying again.

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

提示:
1 <= prices.length <= 3 * 10 ^ 4
0 <= prices[i] <= 10 ^ 4

If you need to buy and sell multiple times here, you will buy at each peak and valley as shown in the figure below, and then sell at the closest peak to find all peaks and valleys. Peak.
Why do you want to find all of them? Look at the red line I marked. The line 2-8 is not as long as the line 2-5 plus 4-8.
This is greedy.
Insert picture description here

    public int maxProfit(int[] prices) {
    
    
        int ret=0, len = prices.length;
        int i=0;
        //遍历一遍即可
        while(i<len-1){
    
    
        	//找出峰谷
            while(i<len-1 && prices[i]>=prices[i+1]) i++;
            int min = prices[i];
            //找出峰顶
            while(i<len-1 && prices[i]<=prices[i+1]) i++;
            // 峰顶-峰谷 += ret
            ret += prices[i]-min;
        }
        return ret;
    }
123. The Best Time to Buy and Sell Stock III

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

Given an array, its i-th element is the price of a given stock on the i-th day.
Design an algorithm to calculate the maximum profit you can get. You can complete up to two transactions.
Note: You cannot participate in multiple transactions at the same time (you must sell the previous stocks before buying again).

Example 1:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on the 4th day (stock price = 0), and on the 6th day (stock price = 3) When you sell, the exchange can make a profit = 3-0 = 3.
Then, buy on the 7th day (stock price = 1), and sell on the 8th day (stock price = 4). This exchange can make a profit = 4-1 = 3.

Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on the 1st day (stock price = 1), and sell on the 5th day (stock price = 5) , This exchange can make a profit = 5-1 = 4.
Note that you cannot buy stocks one after another on the first and second days and then sell them later.
Because this is involved in multiple transactions at the same time, you must sell the previous stocks before buying again.

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

There is a limit of two transactions here. Here is a simple and well-understood idea:
profits[i]: record the profit of buying at the lowest price MIN from 0 to i and selling at the current price prices[i], so profits[i ]=prices[i]
-Sweep MIN from right to left again to find the maximum profit in the interval i ~ n-1 maxProfit = max{maximum selling price MAX-buying price}
Then the final result ans=max{profits[ i-1]+value}

public int maxProfit(int[] prices) {
    
    
        if(prices == null || prices.length <= 0) return 0;
        int len = prices.length;
        /**
         * profits[i]表示在min买入,在第i天以prices[i]价格卖出时的利润
         * profits[i]的意义在于: 保证第一次交易完全是在第i天前, 与后面的股价无关
         */
        int[] profits = new int[len];
        profits[0] = 0;
        // min为最小买入价
        int min = prices[0];
        for (int i = 1; i < len; i++) {
    
    
            if (min > prices[i]) {
    
    
                min = prices[i];
            }
            // 买入价为min,第i天卖出
            profits[i] = prices[i] - min;
        }

        int maxPrice = 0;  //max为最大卖出价
        int maxProfit = profits[len-1]; //两次交易的最大利润默认为第一次最后一天的交易利润, 因为可能不存在第二次交易
        int secMaxProfit = 0;  //第二次卖出的最大利润
        for (int i = len - 1; i > 0; i--) {
    
    
            if (prices[i] > maxPrice) maxPrice = prices[i]; //更新最大卖出价
            secMaxProfit = Math.max(secMaxProfit, maxPrice - prices[i]);  //第i天以prices[i]买入,以最高股价卖出获得的利润
            /**
             * [重点]:
             * profits[i - 1] : 第i-1天第一次卖出的最大利润 (注意:第一次买入是在第i-1之前)
             * secMaxProfit : 第i天买入, 在第i天后以最高价卖出的最大利润
             * 假设以i天作为分割点,在第i天前进行第一次交易获得的利润 + 第i天后第二次交易获得的利润 = 两次交易的利润
             */
            maxProfit = Math.max(maxProfit, profits[i - 1] + secMaxProfit);
        }
        return maxProfit;
    }
188. The best time to buy and sell stock IV* (I didn't solve it, I only worked as a porter for the problem)

Given an integer array prices, its i-th element prices[i] is the price of a given stock on the i-th day.
Design an algorithm to calculate the maximum profit you can get. You can complete k transactions at most.
Note: You cannot participate in multiple transactions at the same time (you must sell the previous stocks before buying again).

Example 1:
Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (stock price = 2), and on day 2 (stock price = 4) Sell, this exchange can make a profit = 4-2 = 2

Example 2:
Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on the second day (stock price = 2), and on the third day (stock Price = 6) when you sell, the exchange can make a profit = 6-2 = 4.
Then, buy on the 5th day (stock price = 0) and sell on the 6th day (stock price = 3). The exchange can make a profit = 3-0 = 3.

Guess you like

Origin blog.csdn.net/qq_45531729/article/details/110939309