股票买卖最佳时机

int maxProfit(vector<int>& prices) {
        int sz = prices.size();
        if (0 == sz) return 0;
        int min_idx = 0;
        int max_val = 0;
        for (int i = 1; i < sz; ++i) {
            if (prices[min_idx] > prices[i]) {
                min_idx = i;
                continue;
            }
            max_val = std::max(max_val, (prices[i] - prices[min_idx]));
        }
        return max_val;
    }

2

int maxProfit(vector<int>& prices) {
        int total = 0;
        int sz = prices.size();
        if (0 == sz) return 0;
        std::vector<int> d;
        d.resize(sz, 0);
        for (int i = 1; i < sz; ++i) {
            d[i] = prices[i] - prices[i - 1];
        }
        for(int i = 0; i < sz; ++i) {
            if (d[i] > 0) {
                total += d[i];
            }
        }
        return total;
    }
posted @ 2021-07-13 11:34  cyssmile  阅读(41)  评论(0)    收藏  举报