LeetCode Brush Questions: Greedy Algorithm [122. The best time to buy and sell stocks II] - Java version

Greedy Algorithms: Interval Problems

I just record my own process of brushing the questions, and I have referred to various solutions for the answers.

Thank you for correcting me if I make any mistakes!

Reference: ① LeetCode 101: A LeetCode Grinding Guide (C++ Version) Author: Gao Chang Chang Gao

           ②Code  Caprice (programmercarl.com)  Author: Programmer Carl

Source of questions: Question Bank - LeetCode, the global geek's favorite technology growth platform (leetcode-cn.com)

My own thinking: choose a low to buy, choose a high to sell, and choose a low to buy...the cycle repeats.

Result: Too much trouble, and the specific implementation has many bugs.

// 实现不了,有数组越界的空指针异常
while (i < prices.length) {
    if (start >= prices[i]) {
    	start = prices[i++];
    } else {
        int end = prices[i];
        while (i < prices.length) {
            ······
  • The final profit can be decomposed into the sum of the daily income. If you buy on the 0th day and sell on the 3rd day, then the profit is: prices[3] - prices[0]. Equivalent to (prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0]).

  • Decompose the profit into the dimension of the unit of each day, rather than consider the overall interval! Then the daily profit sequence can be obtained according to prices: (prices[i] - prices[i - 1]).....(prices[1] - prices[0]).

  • There is no profit on the first day, and there will be no profit until at least the second day, so the series of profits is one day less than the series of stocks.

  • It can be seen from the figure that in fact, we only need to collect daily positive profits. The range of collecting positive profits is the range of stock trading, and we only need to pay attention to the final profit without recording the range . Then only collecting positive profits is where greed comes in!

  • Local Optimum: Collect daily positive profits; Global Optimum: Find the maximum profit.

public int maxProfit(int[] prices) {
int sum = 0;
    for (int i = 1; i < prices.length; i++) {
    	sum += Math.max(prices[i] - prices[i - 1], 0); //只收集每天的正利润
    }
    return sum;
}

Guess you like

Origin blog.csdn.net/weixin_51909882/article/details/122165881