LeetCode 121. Best Time to Buy and Sell Stock

来源:互联网 发布:常见电信网络诈骗试题 编辑:程序博客网 时间:2024/04/30 15:23

描述

给出连续几天股票的波动,问可以获得的最大收益

解决

首先要知道,股票是要先买入,然后再卖出的。比较暴力的就是O(n^2)遍历啦,但是可以用O(n)的方法,在遍历的过程中记录到当前位置最小的值,然后做减法进行比较统计就可以了。

class Solution {public:    int maxProfit(vector<int>& prices) {        int lenth = prices.size();        if (lenth == 0){            return 0;        }        int max_val = 0;        int tmp = prices[0];        for (int i = 1; i < lenth; ++i){            tmp = tmp > prices[i] ? prices[i] : tmp;            max_val = max_val < prices[i] - tmp ? prices[i] - tmp : max_val;        }        return max_val;    }};
0 0
原创粉丝点击