您的位置:首页 > 其它

leetcode刷题。总结,记录,备忘 122

2015-07-26 14:43 309 查看
leetcode刷题122Best 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).
这个题其实很简单,感觉比 I 版都简单点,就是允许多次购买,然后计算总数,所以只需要计算每个连续的升序的序列的头尾差值,然后相加得到总和即可。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.size() == 0)
        return 0;
        int min = *prices.begin();
        int temp = 0, sum = 0;
        for (vector<int>::iterator it =prices.begin(); it != prices.end()-1; ++it)
        {
            if (*it > *(it+1))
            {
                min = *(it+1);
                sum += temp;
                temp = 0;
                continue;
            }
            else
            {
                temp = *(it+1) - min;
            }
        }
        sum += temp;
        
        return sum;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: