0%

[Leetcode]122. Best Time to Buy and Sell Stock II (C++)

题目描述

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

Say you have an array prices 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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

例子

例子 1

Input: [7,1,5,3,6,4]
Output: 7
Explaination:Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

例子 2

Input: [1,2,3,4,5]
Output: 4
Explaination:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.

例子 3

Input: [7,6,4,3,1]
Output: 0
Explaination:In this case, no transaction is done, i.e. max profit = 0.

Note

  • 1 <= prices.length <= 3 * 10 ^ 4
  • 0 <= prices[i] <= 10 ^ 4

解题思路

这道题和前一道买卖股票:121. Best Time to Buy and Sell Stock 的区别在于可以重复多次购买。那么思路就更简单了,用贪心的思路:只要遇到低价就买,遇到高价就卖;相当于每一天只要遇到比前一天的价格高就卖出再重新买入,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int maxProfit(std::vector<int>& prices) {
if (prices.empty()) return 0;

int profit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}

return profit;
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)