Skip to content

Commit ed62a18

Browse files
Update 122. 买卖股票的最佳时机 II.md
1 parent 87417c5 commit ed62a18

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

Dynamic Programming/122. 买卖股票的最佳时机 II.md

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444

4545
---
4646

47-
动态规划:
47+
贪心/动态规划:
4848

4949
一次遍历。`dp[i]` 表示从第一天到第 `i + 1` 天内的最大利润(并不意味着第 `i + 1` 天卖出股票),其值要么是上一个值,要么是上一个值加上**当前价格与昨天价格的差**(这样做的原因是题目中允许当天购买和出售),最后返回数组最后一位值即可。
5050

@@ -58,5 +58,19 @@ class Solution {
5858
}
5959
return dp[n - 1];
6060
}
61+
```
62+
63+
**贪心**:由于题目允许当天购买和出售,因此只要前后两天收益差值大于零就可以计入股票收益中。
64+
65+
```go
66+
func maxProfit(prices []int) int {
67+
ans := 0
68+
for i := 1; i < len(prices); i++ {
69+
ans += max(0, prices[i] - prices[i - 1])
70+
}
71+
return ans
6172
}
62-
```
73+
```
74+
75+
76+

0 commit comments

Comments
 (0)