121. Best Time to Buy and Sell Stock(easy)

版权声明:文章都是原创,转载请注明~~~~ https://blog.csdn.net/SourDumplings/article/details/88627121

Easy

2273113FavoriteShare

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

C++:

蛮力算法:

/*
 * @Author: SourDumplings
 * @Link: https://github.com/SourDumplings/
 * @Email: [email protected]
 * @Description: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
 * @Date: 2019-03-17 20:54:01
 */

class Solution
{
  public:
    int maxProfit(vector<int> &prices)
    {
        int n = prices.size();
        int max = 0;
        for (int i = 0; i < n; i++)
        {
            int money = prices[i];
            for (int j = i + 1; j < n; j++)
            {
                int profit = prices[j] > money ? prices[j] - money : 0;
                if (profit > max)
                {
                    max = profit;
                }
            }
        }
        return max;
    }
};

One Pass算法:

/*
 * @Author: SourDumplings
 * @Link: https://github.com/SourDumplings/
 * @Email: [email protected]
 * @Description: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
 * @Date: 2019-03-17 21:09:26
 * 
 * 这个方法真心神奇,这么维护两个变量都可以,是不是启示买股票的方法嘞?
 */

class Solution
{
  public:
    int maxProfit(vector<int> &prices)
    {
        int minPrice = INT_MAX;
        int maxProfit = 0;
        for (auto &i : prices)
        {
            if (i < minPrice)
            {
                minPrice = i;
            }
            else if (i - minPrice > maxProfit)
            {
                maxProfit = i - minPrice;
            }
        }
        return maxProfit;
    }
};

猜你喜欢

转载自blog.csdn.net/SourDumplings/article/details/88627121
今日推荐