diff --git a/include/s0122_best_time_to_buy_and_sell_stock_ii.hpp b/include/s0122_best_time_to_buy_and_sell_stock_ii.hpp new file mode 100644 index 0000000..14c7bb2 --- /dev/null +++ b/include/s0122_best_time_to_buy_and_sell_stock_ii.hpp @@ -0,0 +1,14 @@ +#ifndef S0122_BEST_TIME_TO_BUY_AND_SELL_STOCK_II_HPP +#define S0122_BEST_TIME_TO_BUY_AND_SELL_STOCK_II_HPP + +#include +#include + +using namespace std; + +class S0122 { + public: + int maxProfit(vector& prices); +}; + +#endif diff --git a/notes/src/SUMMARY.md b/notes/src/SUMMARY.md index 4763517..62de650 100644 --- a/notes/src/SUMMARY.md +++ b/notes/src/SUMMARY.md @@ -57,6 +57,7 @@ - [基础问题](./dynamic-programming-basic.md) - [背包问题](./knapsack.md) - [打家劫舍](./house-robber.md) +- [股票问题](./stock.md) # STL diff --git a/notes/src/stock.md b/notes/src/stock.md new file mode 100644 index 0000000..6f31fbc --- /dev/null +++ b/notes/src/stock.md @@ -0,0 +1,18 @@ +# 股票问题 + +## [122. 买卖股票的最佳时机 II](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/) + +- `dp[i][0]` 表示第 i 天持有股票情况下的资产总额,`dp[i][1]` 表示第 i 天没有持有股票情况下的资产总额。这里的资产不包括股票本身的价值,只包括自身的现金,如果你在第 1 天买入了股票,那么你的资产总额是 `-prices[0]`。 +- 递推公式: + - 我们先来讨论 `dp[i][0]`,也就是第 i 天持有股票时的资产,分两种情况 + - 第 i - 1 天持有股票,那么第 i 天的资产就是 `dp[i - 1][0]` + - 第 i - 1 天没持有股票,那么第 i 天的资产就是 `dp[i - 1][1] - prices[i]` + - 取这两者的最大值即为第 i 天的最大资产 `dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])` + - 同理 `dp[i][1]` 也分两种情况 + - 第 i - 1 天持有股票,那么第 i 天的资产就是 `dp[i - 1][0] + prices[0]` + - 第 i - 1 天没持有股票,那么第 i 天的资产就是 `dp[i - 1][1]` + - 取这两者的最大值即为第 i 天的最大资产 `dp[i][1] = max(dp[i - 1][0] + prices[i], dp[i - 1][1])` +- 初始化 + - `dp[0][0] = -prices[0]` + - `dp[0][1] = 0` +- 遍历顺序:从前往后 diff --git a/src/s0122_best_time_to_buy_and_sell_stock_ii.cpp b/src/s0122_best_time_to_buy_and_sell_stock_ii.cpp new file mode 100644 index 0000000..0770098 --- /dev/null +++ b/src/s0122_best_time_to_buy_and_sell_stock_ii.cpp @@ -0,0 +1,12 @@ +#include "s0122_best_time_to_buy_and_sell_stock_ii.hpp" + +int S0122::maxProfit(vector& prices) { + int len = prices.size(); + vector> dp(len, vector{0, 0}); + dp[0][0] = -prices[0]; + for (int i{1}; i < len; ++i) { + dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]); + dp[i][1] = max(dp[i - 1][0] + prices[i], dp[i - 1][1]); + } + return max(dp[len - 1][1], 0); +} diff --git a/tests/s0122_best_time_to_buy_and_sell_stock_ii.cpp b/tests/s0122_best_time_to_buy_and_sell_stock_ii.cpp new file mode 100644 index 0000000..57f30aa --- /dev/null +++ b/tests/s0122_best_time_to_buy_and_sell_stock_ii.cpp @@ -0,0 +1,17 @@ +#include "s0122_best_time_to_buy_and_sell_stock_ii.hpp" + +#include + +TEST(Problem122, Case1) { + vector prices{7, 1, 5, 3, 6, 4}; + int expected{7}; + S0122 solution; + EXPECT_EQ(solution.maxProfit(prices), expected); +} + +TEST(Problem122, Case2) { + vector prices{7, 6, 4, 3, 1}; + int expected{0}; + S0122 solution; + EXPECT_EQ(solution.maxProfit(prices), expected); +}