20240409 Finished

This commit is contained in:
jackfiled 2024-04-09 16:09:15 +08:00
parent 1c8d953382
commit 38eeba1ce7
2 changed files with 40 additions and 1 deletions

View File

@ -97,3 +97,4 @@ mod p27_remove_element;
mod p80_remove_duplicates_from_sorted_array_ii; mod p80_remove_duplicates_from_sorted_array_ii;
mod p169_majority_element; mod p169_majority_element;
mod p189_rotate_array; mod p189_rotate_array;
mod p121_best_time_to_buy_and_sell_stock;

View File

@ -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>) -> 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]));
}
}