leetcode Best Time to Buy and Sell Stock II

和上一题类似Best Time to Buy and Sell Stock,这里还是用一个数组存每天股票价格,你有很多次买入卖出的机会,但是每次买入要在前一次卖出前。

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

思路就和上一题不一样了,应该用贪心策略,每次买入都要有收益才买入,例如,当前的价格比第二题的高的话就不买入,如果比第二天的低那果断买入,起码我第二题卖掉就有赚了。然后什么时候卖出是个要注意的,例如,1,2,3,2,5,6,那么第一次在1买入,因为2比1大,然后我们看3,比2大,所以可以到3再卖出因为和你1买入2卖出再买入2再卖出3的收益是一样的。所以2被跳过,但是现在到3之后的2了,3到2会损失,那是我们不能允许的。所以3就要卖出。然后当前就从3之后的2开始考虑,继续如上考虑,最后就可以获得做大收益。

class Solution {
public:
    int maxProfit(vector<int> &prices) 
    {
        int len = prices.size();
        int profit = 0, i = 0, maxInd = 0, curp = 0;
        while(i < len - 1)
        {
            if (prices[i] >= prices[i+1])
            {
                i++;
                continue;
            }
            maxInd = i + 1;
            curp = prices[i];
            while(i + 1 < len && prices[i] <= prices[i+1])
            {
                maxInd = i+1;
                i++;
            }
            profit += prices[maxInd] - curp;
            i = maxInd + 1;
        }
        return profit;
    }
};

 

posted on 2014-12-02 21:45  higerzhang  阅读(212)  评论(0编辑  收藏  举报