309. Best Time to Buy and Sell Stock with Cooldown

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) with the following restrictions:

• You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
• After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

```Input: [1,2,3,0,2]
Output: 3
```

309. Best Time to Buy and Sell Stock with Cooldown
``````struct Solution;
use std::i32;

impl Solution {
fn max_profit(prices: Vec<i32>) -> i32 {
let n = prices.len();
if n == 0 {
return 0;
}
let mut buy: Vec<i32> = vec![0; n];
let mut sell: Vec<i32> = vec![0; n];
let mut rest: Vec<i32> = vec![0; n];
sell = i32::MIN;
for i in 1..n {
sell[i] = i32::max(buy[i - 1] + prices[i], sell[i - 1]);
rest[i] = i32::max(sell[i - 1], rest[i - 1]);
}
i32::max(sell[n - 1], rest[n - 1])
}
}

#[test]
fn test() {
let prices: Vec<i32> = vec![1, 2, 3, 0, 2];
let res = 3;
assert_eq!(Solution::max_profit(prices), res);
}
``````