更新了121的一维数组优化空间的java代码注释

This commit is contained in:
LiHua
2021-11-24 16:19:34 +08:00
parent 30886018c4
commit 95a8752dd5

View File

@ -194,7 +194,7 @@ public:
## 其他语言版本 ## 其他语言版本
Java ### Java
> 贪心法: > 贪心法:
@ -242,11 +242,12 @@ class Solution {
class Solution { class Solution {
public int maxProfit(int[] prices) { public int maxProfit(int[] prices) {
int[] dp = new int[2]; int[] dp = new int[2];
// 记录一次交易,一次交易有买入卖出两种状态
// 0代表持有1代表卖出
dp[0] = -prices[0]; dp[0] = -prices[0];
dp[1] = 0; dp[1] = 0;
// 可以参考斐波那契问题的优化方式 // 可以参考斐波那契问题的优化方式
// dp[0] 和 dp[1], 其实是第 0 天的数据 // 我们从 i=1 开始遍历数组,一共有 prices.length 天,
// 所以我们从 i=1 开始遍历数组,一共有 prices.length 天,
// 所以是 i<=prices.length // 所以是 i<=prices.length
for (int i = 1; i <= prices.length; i++) { for (int i = 1; i <= prices.length; i++) {
// 前一天持有;或当天买入 // 前一天持有;或当天买入
@ -263,7 +264,7 @@ class Solution {
} }
``` ```
Python ### Python
> 贪心法: > 贪心法:
```python ```python
@ -307,7 +308,8 @@ class Solution:
return dp[(length-1) % 2][1] return dp[(length-1) % 2][1]
``` ```
Go ### Go
```Go ```Go
func maxProfit(prices []int) int { func maxProfit(prices []int) int {
length:=len(prices) length:=len(prices)
@ -334,7 +336,7 @@ func max(a,b int)int {
} }
``` ```
JavaScript ### JavaScript
> 动态规划 > 动态规划