Add stock
All checks were successful
ci/woodpecker/push/test Pipeline was successful

This commit is contained in:
Sainnhe Park 2023-02-09 21:34:48 +08:00
parent b8d1550a43
commit 331178cb2c
5 changed files with 62 additions and 0 deletions

View File

@ -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 <algorithm>
#include <vector>
using namespace std;
class S0122 {
public:
int maxProfit(vector<int>& prices);
};
#endif

View File

@ -57,6 +57,7 @@
- [基础问题](./dynamic-programming-basic.md) - [基础问题](./dynamic-programming-basic.md)
- [背包问题](./knapsack.md) - [背包问题](./knapsack.md)
- [打家劫舍](./house-robber.md) - [打家劫舍](./house-robber.md)
- [股票问题](./stock.md)
# STL # STL

18
notes/src/stock.md Normal file
View File

@ -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`
- 遍历顺序:从前往后

View File

@ -0,0 +1,12 @@
#include "s0122_best_time_to_buy_and_sell_stock_ii.hpp"
int S0122::maxProfit(vector<int>& prices) {
int len = prices.size();
vector<vector<int>> dp(len, vector<int>{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);
}

View File

@ -0,0 +1,17 @@
#include "s0122_best_time_to_buy_and_sell_stock_ii.hpp"
#include <gtest/gtest.h>
TEST(Problem122, Case1) {
vector<int> prices{7, 1, 5, 3, 6, 4};
int expected{7};
S0122 solution;
EXPECT_EQ(solution.maxProfit(prices), expected);
}
TEST(Problem122, Case2) {
vector<int> prices{7, 6, 4, 3, 1};
int expected{0};
S0122 solution;
EXPECT_EQ(solution.maxProfit(prices), expected);
}