rustgym/leetcode/
_309_best_time_to_buy_and_sell_stock_with_cooldown.rs1struct Solution;
2use std::i32;
3
4impl Solution {
5 fn max_profit(prices: Vec<i32>) -> i32 {
6 let n = prices.len();
7 if n == 0 {
8 return 0;
9 }
10 let mut buy: Vec<i32> = vec![0; n];
11 let mut sell: Vec<i32> = vec![0; n];
12 let mut rest: Vec<i32> = vec![0; n];
13 sell[0] = i32::MIN;
14 buy[0] = -prices[0];
15 for i in 1..n {
16 buy[i] = i32::max(rest[i - 1] - prices[i], buy[i - 1]);
17 sell[i] = i32::max(buy[i - 1] + prices[i], sell[i - 1]);
18 rest[i] = i32::max(sell[i - 1], rest[i - 1]);
19 }
20 i32::max(sell[n - 1], rest[n - 1])
21 }
22}
23
24#[test]
25fn test() {
26 let prices: Vec<i32> = vec![1, 2, 3, 0, 2];
27 let res = 3;
28 assert_eq!(Solution::max_profit(prices), res);
29}