Browse Source

feat: best_time_to_buy_and_sell_stock2

Zhang Li 1 year ago
parent
commit
ef6070edee
2 changed files with 40 additions and 0 deletions
  1. 39 0
      src/solutions/dp/best_time_to_buy_and_sell_stock2.rs
  2. 1 0
      src/solutions/dp/mod.rs

+ 39 - 0
src/solutions/dp/best_time_to_buy_and_sell_stock2.rs

@@ -0,0 +1,39 @@
+struct Solution;
+
+
+
+impl Solution {
+    // dp[i] = max_{0<=k<=i} {dp[k-1] + prices[i] - prices[k]}
+    pub fn max_profit(prices: Vec<i32>) -> i32 {
+        let l = prices.len();
+        let mut dp = vec![0; l];
+
+        for i in 0..l {
+            for k in 0..=i {
+                // k 为上一次买入的时间
+                if k == 0 {
+                    dp[i] = dp[i].max(prices[i] - prices[0]);
+                } else {
+                    dp[i] = dp[i].max(dp[k-1] + (prices[i] - prices[k]));
+                }
+
+            }
+        }
+
+
+        dp[l-1]
+
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_max_profit() {
+        let prices = vec![7,1,5,3,6,4];
+        let res = Solution::max_profit(prices);
+        assert_eq!(res, 7);
+    }
+}

+ 1 - 0
src/solutions/dp/mod.rs

@@ -12,3 +12,4 @@ mod edit_distance2;
 mod decode_ways;
 mod unique_binary_search_trees;
 mod distinct_subsequences;
+mod best_time_to_buy_and_sell_stock2;