[leetcode]Best Time to Buy and Sell Stock

水题,就是找aj - ai 最大 j > i

一般就是o(n^2),不过从左到右扫一遍就好了复杂度O(n)

只需要记录最小的就ok.

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int minx = 0;
        int ans = 0;
        for(int i = 0 ; i < prices.size() ; i++){
            if(prices[i] < prices[minx]) minx = i;
            if(prices[i] - prices[minx] > ans) ans = prices[i] - prices[minx];     
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/x1957/p/3276229.html