Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4005d49

Browse files
committed
buy sell stocks 2
1 parent 5166971 commit 4005d49

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

‎src/best_time_stock_cooldown.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}

‎src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
mod longest_common_subseq;
1+
mod best_time_stock_cooldown;
22
fn main() {}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /