LeetCode 121: Best Time to Buy and Sell Stock

題目鏈接:

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

描述

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

輸入

輸入一個數組。

輸出

最大利潤。

樣例輸入

[7, 1, 5, 3, 6, 4]
[7, 6, 4, 3, 1]

樣例輸出

5
0

算法思想:

剛開始使用兩次循環遍歷,結果超時,後來改爲一次循環,AC通過。
一次循環,使用mini記錄之前最小的價格,ans之前的結果,如果當前數小於mini,則更新mini爲當前數,否則如果ans小於prices[i] - mini,則更新ans。循環遍歷完,ans存放的即爲最大利潤值。

源代碼

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int sz = prices.size();
        if (sz == 0)
            return 0;
        int ans = 0, mini = prices[0];
        for (int i = 0; i < sz; i++)
        {
            if (prices[i] < mini)
            {
                mini = prices[i];
            }
            else
            {
                if (ans < prices[i] - mini)
                {
                    ans = prices[i] - mini;
                }
            }
        }
        return ans;
    }
};

算法複雜度:

由源代碼可知,算法只有一次循環,故時間複雜度爲O(n)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章