【LeetCode】122. The best time to buy and sell stocks II

1. Title

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:

输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
     随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3

Example 2:

输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
     因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。

Example 3:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0

prompt:

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

Two, solve

1. Greedy

Ideas:

Here we use a greedy idea to solve, and use local optimal accumulation to finally get the overall optimal result.

For example: as shown in the figure below, the abscissa is 3-7, MaxHeight = D = A+B+C.
greedy
Code:

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
  
        int result = 0;
        for (int i=1; i<prices.length; i++) 
            result += Math.max(prices[i]-prices[i-1], 0);    
        return result;
    }
}

Time complexity: O(n)
Space complexity: O(1)

Three, reference

1、Three lines in C++, with explanation
2、Explanation for the dummy like me.
3、Shortest and fastest solution with explanation. You can never beat this.

Guess you like

Origin blog.csdn.net/HeavenDan/article/details/108447902