Best Time to Buy and Sell Stock - LeetCode

題目連接

Best Time to Buy and Sell Stock - LeetCodeblog

注意點

  • 在賣出以前必需要先購入

解法

解法一:遍歷一遍,隨時記錄當前數字以前的最小的數字。將當前數字與當前最小數字相減查看收益。時間複雜度O(n)leetcode

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

小結

相關文章
相關標籤/搜索