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