leetcode Best Time to Buy and Sell Stock II

来源:互联网 发布:怎样做淘宝优惠群 编辑:程序博客网 时间:2024/06/06 02:52

分析:题目的意思是整个过程中只能买一只股票然后卖出,也可以不买股票。也就是我们要找到一对最低价和最高价,最低价在最高价前面,以最低价买入股票,以最低价卖出股票。可以买卖多次股票,但是不能连续买股票,也就是说手上最多只能有一只股票(注意:可以在同一天卖出手上的股票然后再买进)

算法复杂度:O(n)


思路:

找到所有递增区间的利润。按照股票差价构成新数组 prices[1]-prices[0], prices[2]-prices[1], prices[3]-prices[2], ..., prices[n-1]-prices[n-2]。把数组中所有差价为正的值加起来就是最大利润了。因为只有递增区间内的差价是正数,并且同一递增区间内所有差价之和 = 区间最大价格 -  区间最小价格


int maxProfit(vector<int> &prices){        int n = prices.size();        if(n<=1) return 0;        int profit=0;        //所有差值为正的相加        for(int i=1; i<n; i++){            int dif = prices[i]-prices[i-1];            if(dif>0)            {                profit += dif;            }        }        return profit;    }


0 0
原创粉丝点击