[LeetCode] 122. The best time to buy and sell stocks II (C++)

1 topic description

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).

2 Example description

2.1 Example 1

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

2.2 Example 2

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (stock price = 1), sell on day 5 (stock price = 5), this The exchange can make a profit = 5-1 = 4.
Note that you cannot buy stocks one after another on the first day and the second day, 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.

2.3 Example 3

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

3 Problem solving tips

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

4 Problem-solving ideas

Stock trading is based on the price of several days after subtracting the price of the previous day, and the following method can be used.

5 Detailed source code (C++)

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int res = 0 ;
        //股票不管你怎么买卖都是后若干天的价格减去前一天的价格。
        for ( int i = 0 ; i < prices.size() - 1 ; i ++ )
        {
    
    
            res = res + max ( 0 , prices[i + 1] - prices[i] ) ;
        }
        return res ;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114286520