mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2026-02-02 18:39:09 +08:00
Merge branch 'master' into master
This commit is contained in:
@@ -227,8 +227,34 @@ func max(a, b int) int {
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
func maxProfit(prices []int) int {
|
||||
//创建数组
|
||||
dp:=make([][]int,len(prices))
|
||||
for i:=0;i<len(prices);i++{
|
||||
dp[i]=make([]int,2)
|
||||
}
|
||||
dp[0][0]=-prices[0]
|
||||
dp[0][1]=0
|
||||
for i:=1;i<len(prices);i++{
|
||||
dp[i][0]=max(dp[i-1][0],dp[i-1][1]-prices[i])
|
||||
dp[i][1]=max(dp[i-1][1],dp[i-1][0]+prices[i])
|
||||
}
|
||||
return dp[len(prices)-1][1]
|
||||
}
|
||||
func max(a,b int)int{
|
||||
if a<b{
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
Javascript:
|
||||
```javascript
|
||||
// 方法一:动态规划(dp 数组)
|
||||
const maxProfit = (prices) => {
|
||||
let dp = Array.from(Array(prices.length), () => Array(2).fill(0));
|
||||
// dp[i][0] 表示第i天持有股票所得现金。
|
||||
@@ -249,6 +275,21 @@ const maxProfit = (prices) => {
|
||||
|
||||
return dp[prices.length -1][0];
|
||||
};
|
||||
|
||||
// 方法二:动态规划(滚动数组)
|
||||
const maxProfit = (prices) => {
|
||||
// 滚动数组
|
||||
// have: 第i天持有股票最大收益; notHave: 第i天不持有股票最大收益
|
||||
let n = prices.length,
|
||||
have = -prices[0],
|
||||
notHave = 0;
|
||||
for (let i = 1; i < n; i++) {
|
||||
have = Math.max(have, notHave - prices[i]);
|
||||
notHave = Math.max(notHave, have + prices[i]);
|
||||
}
|
||||
// 最终手里不持有股票才能保证收益最大化
|
||||
return notHave;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -257,4 +298,4 @@ const maxProfit = (prices) => {
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码.jpg width=450> </img></div>
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
||||
Reference in New Issue
Block a user