【LeetCode】122. Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock II

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).

 

核心思想:每一段单调递增区间的收益累加。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int m = prices.size();
        if(m == 0)
            return 0;
            
        int ret = 0;
        int buy = prices[0];
        int last = prices[0];
        for(int i = 1; i < m; i ++)
        {
            if(prices[i] < last)
            {
                ret += (last - buy);
                buy = prices[i];
            }
            last = prices[i];
        }
        ret += (last - buy);
        return ret;
    }
};

posted @ 2014-06-02 13:09  陆草纯  阅读(2764)  评论(0编辑  收藏  举报