The best time to buy and sell stocks LeetCode # 121

Topics address

The best time to stock trading

The best time to stock trading

Given an array, which i-th element is a given stock i-day prices.

If you are only allowed up to complete a transaction (ie buying and selling a stock), to design an algorithm to compute the maximum profit you can get.

Note that you can not sell the stock before buying stocks.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Day 2 (= 1 stock price), when buying, on day 5 (stock price = 6), when sold, The maximum profit = 6-1 = 5.
Note that profits can not be 7-1 = 6, because the selling price must be greater than the purchase price. \

Example 2:

Enter: [7,6,4,3,1]
Output: 0
to explain: In this case, no transaction is completed, the maximum profit is zero.

Thinking

Violence 1.
[7,1,5,3,6,4]
Take 7, a view from the end to all numbers greater than 7, the difference operator, taking the maximum
take a view from the end of all greater than 5 to 1 number, count the difference, taking the maximum
...

	 int maxProfit(vector<int>& prices) {
        if (prices.size() < 2)
        {
            return 0;
        }

        int i = 0;
        int maxPrice = 0;
        for (;i < prices.size(); i++)
        {
            int endPos = prices.size() - 1;
            for(int j = endPos; j > i; j--)
            {
                int p = prices[j] - prices[i];
                if(p > 0 && p > maxPrice)
                {
                    maxPrice = p;
                }
            }
        }
        return maxPrice;
    }

Inefficient, time complexity O (n- 2 )

2. traverse
traverse the array again, calculated for each day until the minimum stock price and maximum profit.
Diagram

	 int maxProfit(vector<int>& prices) {
        if (prices.size() < 2)
        {
            return 0;
        }

        int minPrice = INT_MAX;
        int maxPrice = 0;
        for(int i = 0; i < prices.size(); i++)
        {
            if(minPrice > prices[i])
            {
                minPrice = prices[i];
            }
            else if(prices[i] - minPrice > maxPrice)
            {
                maxPrice = prices[i] - minPrice;
            }
        }
        return maxPrice;
    }

reference

Official explanations

Published 39 original articles · won praise 21 · views 30000 +

Guess you like

Origin blog.csdn.net/zbbzb/article/details/104750952