20240409 Finished
This commit is contained in:
parent
1c8d953382
commit
38eeba1ce7
|
@ -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;
|
38
src/problem/p121_best_time_to_buy_and_sell_stock.rs
Normal file
38
src/problem/p121_best_time_to_buy_and_sell_stock.rs
Normal 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]));
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user