|
| 1 | +use std::collections::HashMap; |
| 2 | +pub struct Solution {} |
| 3 | +impl Solution { |
| 4 | + pub fn max_profit(prices: Vec<i32>) -> i32 { |
| 5 | + let mut map: HashMap<(i32, bool), i32> = HashMap::new(); |
| 6 | + Self::dfs(0, true, &prices, &mut map) |
| 7 | + } |
| 8 | + |
| 9 | + fn dfs(i: i32, buy: bool, prices: &Vec<i32>, map: &mut HashMap<(i32, bool), i32>) -> i32 { |
| 10 | + if i > prices.len() as i32 { |
| 11 | + return 0; |
| 12 | + } |
| 13 | + if map.contains_key(&(i, buy)) { |
| 14 | + return *map.get(&(i, buy)).unwrap(); |
| 15 | + } |
| 16 | + let cooldown = Self::dfs(i + 1, buy, prices, map); |
| 17 | + if buy { |
| 18 | + let val = Self::dfs(i + 1, !buy, prices, map) - prices[i as usize]; |
| 19 | + map.insert((i, buy), std::cmp::max(val, cooldown)); |
| 20 | + } else { |
| 21 | + let sell = Self::dfs(i + 2, !buy, prices, map) + prices[i as usize]; |
| 22 | + map.insert((i, buy), std::cmp::max(sell, cooldown)); |
| 23 | + } |
| 24 | + *map.get(&(i, buy)).unwrap() |
| 25 | + } |
| 26 | +} |
0 commit comments