Skip to content

Commit 5740683

Browse files
committed
'Best Time to Buy and Sell Stock III' soln
1 parent 70bf265 commit 5740683

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
///
2+
/// Problem: Best Time to Buy and Sell Stock III
3+
///
4+
/// You are given an array prices where prices[i] is the price of a given stock on the ith day.
5+
///
6+
/// Find the maximum profit you can achieve. You may complete at most two transactions.
7+
///
8+
/// Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock
9+
/// before you buy again).
10+
///
11+
/// Example 1:
12+
/// Input: prices = [3,3,5,0,0,3,1,4]
13+
/// Output: 6
14+
/// Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
15+
/// Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
16+
///
17+
/// Example 2:
18+
/// Input: prices = [1,2,3,4,5]
19+
/// Output: 4
20+
/// Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
21+
/// Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging
22+
/// multiple transactions at the same time. You must sell before buying again.
23+
///
24+
/// Example 3:
25+
/// Input: prices = [7,6,4,3,1]
26+
/// Output: 0
27+
/// Explanation: In this case, no transaction is done, i.e. max profit = 0.
28+
///
29+
/// Constraints:
30+
/// 1 <= prices.length <= 10^5
31+
/// 0 <= prices[i] <= 10^5
32+
///
33+
34+
// # Solution:
35+
// Time complexity: O(n)
36+
// Space complexity: O(1)
37+
38+
39+
impl Solution {
40+
pub fn max_profit(prices: Vec<i32>) -> i32 {
41+
if prices.is_empty() {
42+
return 0;
43+
}
44+
45+
let mut buy1 = -prices[0];
46+
let mut sell1 = 0;
47+
let mut buy2 = -prices[0];
48+
let mut sell2 = 0;
49+
50+
for i in 1..prices.len() {
51+
52+
buy1 = buy1.max(-prices[i]);
53+
54+
sell1 = sell1.max(buy1 + prices[i]);
55+
56+
buy2 = buy2.max(sell1 - prices[i]);
57+
58+
sell2 = sell2.max(buy2 + prices[i]);
59+
}
60+
61+
62+
sell2
63+
}
64+
}

0 commit comments

Comments
 (0)