mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
为 0122买卖股票的最佳时机II Java代码添加注释
This commit is contained in:
@ -136,24 +136,31 @@ Java:
|
|||||||
```java
|
```java
|
||||||
// 动态规划
|
// 动态规划
|
||||||
class Solution
|
class Solution
|
||||||
|
// 实现1:二维数组存储
|
||||||
|
// 可以将每天持有与否的情况分别用 dp[i][0] 和 dp[i][1] 来进行存储
|
||||||
|
// 时间复杂度:O(n),空间复杂度O(n)
|
||||||
public int maxProfit(int[] prices) {
|
public int maxProfit(int[] prices) {
|
||||||
int n = prices.length;
|
int n = prices.length;
|
||||||
int[][] dp = new int[n][2];
|
int[][] dp = new int[n][2]; // 创建二维数组存储状态
|
||||||
dp[0][0] = 0;
|
dp[0][0] = 0; // 初始状态
|
||||||
dp[0][1] = -prices[0];
|
dp[0][1] = -prices[0];
|
||||||
for (int i = 1; i < n; ++i) {
|
for (int i = 1; i < n; ++i) {
|
||||||
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
|
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]); // 第 i 天,没有股票
|
||||||
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
|
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]); // 第 i 天,持有股票
|
||||||
}
|
}
|
||||||
return dp[n - 1][0];
|
return dp[n - 1][0]; // 卖出股票收益高于持有股票收益,因此取[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 实现2:变量存储
|
||||||
|
// 第一种方法需要用二维数组存储,有空间开销,其实关心的仅仅是前一天的状态,不关注更多的历史信息
|
||||||
|
// 因此,可以仅保存前一天的信息存入 dp0、dp1 这 2 个变量即可
|
||||||
|
// 时间复杂度:O(n),空间复杂度O(1)
|
||||||
public int maxProfit(int[] prices) {
|
public int maxProfit(int[] prices) {
|
||||||
int n = prices.length;
|
int n = prices.length;
|
||||||
int dp0 = 0, dp1 = -prices[0];
|
int dp0 = 0, dp1 = -prices[0]; // 定义变量,存储初始状态
|
||||||
for (int i = 1; i < n; ++i) {
|
for (int i = 1; i < n; ++i) {
|
||||||
int newDp0 = Math.max(dp0, dp1 + prices[i]);
|
int newDp0 = Math.max(dp0, dp1 + prices[i]); // 第 i 天,没有股票
|
||||||
int newDp1 = Math.max(dp1, dp0 - prices[i]);
|
int newDp1 = Math.max(dp1, dp0 - prices[i]); // 第 i 天,持有股票
|
||||||
dp0 = newDp0;
|
dp0 = newDp0;
|
||||||
dp1 = newDp1;
|
dp1 = newDp1;
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user