|
@@ -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);
|
|
|
+ }
|
|
|
+}
|