Przeglądaj źródła

feat: maximum_product_subarray

Zhang Li 11 miesięcy temu
rodzic
commit
b791f939c1

+ 81 - 0
src/solutions/dp/maximum_product_subarray.rs

@@ -0,0 +1,81 @@
+struct Solution;
+
+impl Solution {
+    pub fn max_product1(nums: Vec<i32>) -> i32 {
+        let n = nums.len();
+        let mut dp1 = vec![0;n];
+        let mut dp2 = vec![0;n];
+        let mut ans = nums[0];
+        dp1[0] = nums[0];
+        dp2[0] = nums[0];
+        for i in 1..n {
+            let value1 = dp1[i-1] * nums[i];
+            let value2 = dp2[i-1] * nums[i];
+
+            dp1[i] = value1.max(value2).max(nums[i]);
+            dp2[i] = value1.min(value2).min(nums[i]);
+
+            ans = ans.max(dp1[i]);
+
+        }
+        // println!("dp: {:?}", dp);
+
+        ans
+
+    }
+
+    pub fn max_product(nums: Vec<i32>) -> i32 {
+        let n = nums.len();
+        let mut dp1 = nums[0];
+        let mut dp2 = nums[0];
+        let mut ans = nums[0];
+
+        for i in 1..n {
+            let value1 = dp1 * nums[i];
+            let value2 = dp2 * nums[i];
+
+            dp1 = value1.max(value2).max(nums[i]);
+            dp2 = value1.min(value2).min(nums[i]);
+
+            ans = ans.max(dp1);
+
+        }
+        // println!("dp: {:?}", dp);
+
+        ans
+
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_max_product() {
+        let nums = vec![2,3,-2,-1,4];
+        let res = Solution::max_product1(nums);
+        assert_eq!(res, 48);
+    }
+
+    #[test]
+    fn test_max_product1() {
+        let nums = vec![2,3,-2,4];
+        let res = Solution::max_product(nums);
+        assert_eq!(res, 6);
+    }
+
+    #[test]
+    fn test_max_product2() {
+        let nums = vec![-2,3,-4];
+        let res = Solution::max_product(nums);
+        assert_eq!(res, 24);
+    }
+
+    #[test]
+    fn test_max_product3() {
+        let nums = vec![2,-5,-2, -4, 3];
+        let res = Solution::max_product(nums);
+        assert_eq!(res, 24);
+    }
+}

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

@@ -18,4 +18,5 @@ mod palindrome_partitioning;
 mod palindrome_partitioning2;
 mod candy;
 mod word_break;
-mod word_break2;
+mod word_break2;
+mod maximum_product_subarray;