forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
309_Best_Time_to_Buy_and_Sell_Stock_with_Cooldown
52 lines (46 loc) · 1.26 KB
/
309_Best_Time_to_Buy_and_Sell_Stock_with_Cooldown
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Leetcode 309: Best Time to Buy and Sell Stock with Cooldown
Detailed video explanation: https://youtu.be/pkiJyNijgBw
=============================================================
C++:
----
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <= 1) return 0;
int A = 0, B = -prices[0], C = 0;
for(int i = 1; i < prices.size(); ++i){
int tmp = A;
A = max(A, C);
C = B + prices[i];
B = max(B, tmp - prices[i]);
}
return max(A, C);
}
};
Java:
----
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1) return 0;
int A = 0, B = -prices[0], C = 0;
for(int i = 1; i < prices.length; ++i){
int tmp = A;
A = Math.max(A, C);
C = B + prices[i];
B = Math.max(B, tmp - prices[i]);
}
return Math.max(A, C);
}
}
Python3:
-------
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1: return 0
A, B, C = 0, -prices[0], 0
for i in range(1, len(prices)):
tmp = A
A = max(A, C)
C = B + prices[i]
B = max(B, tmp - prices[i])
return max(A, C)