Personal algorithm Beginner - greedy algorithm

Keywords: Algorithm greedy algorithm

Example:

The best time to buy and sell stocks II
Given an array prices, where   prices[i] is the price of a given stock on day I.

Design an algorithm to calculate the maximum profit you can make. 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 shares before buying again).

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: if you buy on the second day (stock price = 1) and sell on the third day (stock price = 5), 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). This exchange can make a profit = 6-3 = 3.
Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: if you buy on the first day (stock price = 1) and sell on the fifth day (stock price = 5), this exchange can make a profit = 5-1 = 4.
     Note that you can't buy stocks on day 1 and day 2 and then sell them. Because you are involved in multiple transactions at the same time, you must sell the previous shares before buying again.
Example   3:

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

Tips:

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

---------------------------------------------------------------------------------------------------------------------------------

solve:

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        for(int i = 0;i < prices.length-1; i++){
            if(prices[i] < prices[i+1])  //Local solution to find the optimal solution in a small range
                max += prices[i+1] - prices[i];
        }
        return max;
    }
}

---------------------------------------------------------------------------------------------------------------------------------

Understand the method!!

Greedy algorithm solution
Next, I drew a random stock curve. You can see that if the stock keeps rising, you only need to find the maximum value of the stock rising and the minimum value of the stock starting to rise, and calculate their difference is the maximum profit of the stock during this period of time. If the stock falls, there is no need to calculate. In the end, we only need to accumulate the profits during the period when all the stocks rise, which is the result we require

 

Look at the code


 

public int maxProfit(int[] prices) {
    if (prices == null || prices.length < 2)
        return 0;
    int total = 0, index = 0, length = prices.length;
    while (index < length) {
        //If the stock falls, keep looking until you find the stock and start rising
        while (index < length - 1 && prices[index] >= prices[index + 1])
            index++;
        //The starting value of the stock rise, that is, the minimum value of the rise during this period
        int min = prices[index];
        //Until we find the maximum value of the stock rise
        while (index < length - 1 && prices[index] <= prices[index + 1])
            index++;
        //Calculate the difference of this rising time and add it up
        total += prices[index++] - min;
    }
    return total;
}

/*Author: data structure and algorithm
 Link: https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2zsx1/?discussion=KwAnTs
 Source: LeetCode
 The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.*/

The understanding method diagram comes from leetcode, and the specific algorithm does not use the author's code.

Posted by WhiteHawk on Wed, 20 Oct 2021 11:15:10 -0700