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;
    }
};

小结

相关文章
相关标签/搜索