1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Best Time to Buy and Sell Stock

Posted on 2013-08-22 20:45  1957  阅读(157)  评论(0编辑  收藏  举报

水题,就是找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;
    }
};