小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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

Subscribe to see which companies asked this question

分析

买卖股票II,与 LeetCode(121) Best Time to Buy and Sell Stock的区别就是,此次允许买卖多次,但是必须卖出后才可下次买入。

实际上是求股价波浪线的所有上升段的长度和。

AC代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty())
            return 0;

        int sum = 0;
        //只要后项比前项大,这部分值就一定可以变为利润
        for (size_t i = 1; i < prices.size(); ++i)
        {
            if (prices[i] > prices[i - 1])
                sum += (prices[i] - prices[i - 1]);
        }
        return sum;
    }
};

GitHub测试程序源码

posted on 2015-10-30 16:22  Coding菌  阅读(117)  评论(0编辑  收藏  举报