121. Best Time to Buy and Sell Stock

来源:互联网 发布:mac os 桌面信息白条 编辑:程序博客网 时间:2024/06/16 03:37

121. Best Time to Buy and Sell Stock

思路:
Kadane’s Algorithm

code:

class Solution {public:    //[7, 1, 5, 3, 6, 4]    //[5, 4, 3, 2]    int maxProfit(vector<int>& prices) {        if (prices.size() == 0) return 0;        int min = prices[0];        int max = 0;        for (int i = 1; i < prices.size(); i++) {            if (max < prices[i]-min) max = prices[i] - min;            if (min > prices[i]) min = prices[i];        }        return max;    }};
原创粉丝点击