122. Best Time to Buy and Sell Stock II

  • 46.0%

https://leetcode.com/problems/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).


方法一:

我的代码实现:

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

Second, suppose the first sequence is “a <= b <= c <= d”, the profit is “d - a = (b - a) + (c - b) + (d - c)” without a doubt. And suppose another one is “a <= b >= b’ <= c <= d”, the profit is not difficult to be figured out as “(b - a) + (d - b’)”. So you just target at monotone sequences.

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

python


Basically, if tomorrow’s price is higher than today’s, we buy it today and sell tomorrow. Otherwise, we don’t. Here is the code:

1
2
3
4
5
6
7
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
return sum(max(prices[i+1]-prices[i], 0) for i in range(len(prices)-1))

java


Algorithm

This solution follows the logic used in Approach 2 itself, but with only a slight variation. In this case, instead of looking for every peak following a valley, we can simply go on crawling over the slope and keep on adding the profit obtained from every consecutive transaction. In the end,we will be using the peaks and valleys effectively, but we need not track the costs corresponding to the peaks and valleys along with the maximum profit, but we can directly keep on adding the difference between the consecutive numbers of the array if the second number is larger than the first one, and at the total sum we obtain will be the maximum profit. This approach will simplify the solution. This can be made clearer by taking this example:

[1, 7, 2, 3, 6, 7, 6, 7]

The graph corresponding to this array is:

image

If we analyze the graph, we notice that the points of interest are the consecutive valleys and peaks.

Complexity Analysis

  • Time complexity : O(n)O(n). Single pass.
  • Space complexity : O(1)O(1). Constant space required.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0) return 0;
int i=0;
int maxprofit = 0;
int valley = prices[0];
int peak = prices[0];
while(i<prices.length-1){
while(i<prices.length-1 && prices[i]>=prices[i+1])
i++;
valley = prices[i];
while(i<prices.length-1 && prices[i]<=prices[i+1])
i++;
peak = prices[i];
maxprofit += peak - valley;
}
return maxprofit;
}
}

https://leetcode.com/articles/best-time-buy-and-sell-stock-ii/

Algorithm

This solution follows the logic used in Approach 2 itself, but with only a slight variation. In this case, instead of looking for every peak following a valley, we can simply go on crawling over the slope and keep on adding the profit obtained from every consecutive transaction. In the end,we will be using the peaks and valleys effectively, but we need not track the costs corresponding to the peaks and valleys along with the maximum profit, but we can directly keep on adding the difference between the consecutive numbers of the array if the second number is larger than the first one, and at the total sum we obtain will be the maximum profit. This approach will simplify the solution. This can be made clearer by taking this example:

[1, 7, 2, 3, 6, 7, 6, 7]

The graph corresponding to this array is:
image

From the above graph, we can observe that the sum A+B+CA+B+C is equal to the difference DD corresponding to the difference between the heights of the consecutive peak and valley.

Complexity Analysis

  • Time complexity : O(n)O(n). Single pass.
  • Space complexity: O(1)O(1). Constant space needed.
1
2
3
4
5
6
7
8
9
10
public class Solution {
public int maxProfit(int[] prices) {
int maxprofit = 0;
for(int i=1; i<prices.length; i++){
if(prices[i] - prices[i-1] > 0)
maxprofit += prices[i] - prices[i-1];
}
return maxprofit;
}
}
谢谢你,可爱的朋友。