题目链接:Best Time to Buy and Sell Stock II

Say you have an array for which the i-th 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).

这道题的要求是用数组中的数字表示股票的价格,然后允许随意买入卖出,计算最大利益。

Best Time to Buy and Sell Stock类似的题目,不过这题貌似更容易一些。

把股票的价格想象成折线图,最大的利益就是所有上升的部分之和。因此只要遍历一边数组,当当前元素大于前面的,就将差值累加起来即可。

时间复杂度:O(n)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
class Solution
{
public:
    int maxProfit(vector<int> &prices)
    {
        int res = 0;
        for(int i = 1; i < prices.size(); ++ i)
            res += max(0, prices[i] - prices[i - 1]);
        return res;
    }
};