LeetCode: Best Time to Buy and Sell Stock

思路:记录到当前位置i为止,最小值的位置 min_index, 则到当前位置最大收益就是max( 已有收益, prices[i] - prices[index])。

code:

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


你可能感兴趣的:(LeetCode: Best Time to Buy and Sell Stock)