diff --git a/src/problem/mod.rs b/src/problem/mod.rs index ba63524..0c44635 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -96,4 +96,5 @@ mod p26_remove_duplicates_from_sorted_array; mod p27_remove_element; mod p80_remove_duplicates_from_sorted_array_ii; mod p169_majority_element; -mod p189_rotate_array; \ No newline at end of file +mod p189_rotate_array; +mod p121_best_time_to_buy_and_sell_stock; \ No newline at end of file diff --git a/src/problem/p121_best_time_to_buy_and_sell_stock.rs b/src/problem/p121_best_time_to_buy_and_sell_stock.rs new file mode 100644 index 0000000..f50ad72 --- /dev/null +++ b/src/problem/p121_best_time_to_buy_and_sell_stock.rs @@ -0,0 +1,38 @@ +/** + * [121] Best Time to Buy and Sell Stock + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut result = 0; + let mut min_num = prices[0]; + + for i in 1..prices.len() { + if prices[i] > prices[i - 1] { + result = result.max(prices[i] - min_num); + } else { + if prices[i] < min_num { + min_num = prices[i]; + } + } + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_121() { + assert_eq!(1, Solution::max_profit(vec![1,2])); + } +}