Quellcode durchsuchen

feat: best_time_to_buy_and_sell_stock3

Zhang Li vor 1 Jahr
Ursprung
Commit
66ef838b1e
2 geänderte Dateien mit 61 neuen und 2 gelöschten Zeilen
  1. 58 0
      src/solutions/dp/best_time_to_buy_and_sell_stock3.rs
  2. 3 2
      src/solutions/dp/mod.rs

+ 58 - 0
src/solutions/dp/best_time_to_buy_and_sell_stock3.rs

@@ -0,0 +1,58 @@
+
+struct Solution;
+
+impl Solution {
+    pub fn max_profit(prices: Vec<i32>) -> i32 {
+        let l = prices.len();
+        let mut dp1 = vec![0; l];
+        let mut dp2 = vec![0; l];
+        let mut min_price = i32::MAX;
+        let mut max_price = i32::MIN;
+        let mut res = i32::MIN;
+        for i in 0..l {
+            min_price = min_price.min(prices[i]);
+            dp1[i] = prices[i] - min_price;
+        }
+
+        for i in (0..l).rev() {
+            max_price = max_price.max(prices[i]);
+            if i == l - 1 {
+                dp2[i] = max_price - prices[i];
+            } else {
+                dp2[i] = dp2[i+1].max(max_price - prices[i]);
+            }
+
+        }
+
+        // println!("dp1: {:?}", dp1);
+        // println!("dp2: {:?}", dp2);
+
+        for i in 0..l {
+            res = (dp1[i]+dp2[i]).max(res);
+        }
+
+        res
+
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_max_profit() {
+        let prices = vec![3,3,5,0,0,3,1,4];
+
+        let res = Solution::max_profit(prices);
+        assert_eq!(res, 6);
+    }
+
+    #[test]
+    fn test_max_profit2() {
+        let prices = vec![1,2,3,4,5];
+
+        let res = Solution::max_profit(prices);
+        assert_eq!(res, 4);
+    }
+}

+ 3 - 2
src/solutions/dp/mod.rs

@@ -1,4 +1,3 @@
-mod best_time_to_buy_and_sell_stock;
 mod jump_game_2;
 mod longest_valid_parentheses;
 mod maximum_subarray;
@@ -12,4 +11,6 @@ mod edit_distance2;
 mod decode_ways;
 mod unique_binary_search_trees;
 mod distinct_subsequences;
-mod best_time_to_buy_and_sell_stock2;
+mod best_time_to_buy_and_sell_stock;
+mod best_time_to_buy_and_sell_stock2;
+mod best_time_to_buy_and_sell_stock3;