leetcode_rust/
max_profit.rs

1#![allow(dead_code)]
2
3// eval the diff prices and plus all the postive
4pub fn max_profit(prices: Vec<i32>) -> i32 {
5    if prices.len() < 2 {
6        0
7    } else {
8        let mut profit = 0;
9        for i in 0..prices.len() - 1 {
10            let diff_price = prices[i + 1] - prices[i];
11            if diff_price > 0 {
12                profit += diff_price;
13            }
14        }
15
16        profit
17    }
18}
19
20#[cfg(test)]
21mod tests {
22    use super::*;
23
24    #[test]
25    fn test1() {
26        assert_eq!(max_profit(vec![7, 1, 5, 3, 6, 4]), 7);
27        assert_eq!(max_profit(vec![7, 6, 4, 3, 1]), 0);
28        assert_eq!(max_profit(vec![6, 1, 3, 2, 4, 7]), 7);
29    }
30}