Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitdafd104

Browse files
Merge pull requestyoungyangyang04#483 from jackeyjia/patch-8
add js solution for maxProfit II
2 parentsbabe805 +6eaa76b commitdafd104

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

‎problems/0122.买卖股票的最佳时机II(动态规划).md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,29 @@ class Solution:
201201

202202
Go:
203203

204+
Javascript:
205+
```javascript
206+
constmaxProfit= (prices)=> {
207+
let dp=Array.from(Array(prices.length), ()=>Array(2).fill(0));
208+
// dp[i][0] 表示第i天持有股票所得现金。
209+
// dp[i][1] 表示第i天不持有股票所得最多现金
210+
dp[0][0]=0- prices[0];
211+
dp[0][1]=0;
212+
for(let i=1; i<prices.length; i++) {
213+
// 如果第i天持有股票即dp[i][0], 那么可以由两个状态推出来
214+
// 第i-1天就持有股票,那么就保持现状,所得现金就是昨天持有股票的所得现金 即:dp[i - 1][0]
215+
// 第i天买入股票,所得现金就是昨天不持有股票的所得现金减去 今天的股票价格 即:dp[i - 1][1] - prices[i]
216+
dp[i][0]=Math.max(dp[i-1][0], dp[i-1][1]- prices[i]);
217+
218+
// 在来看看如果第i天不持有股票即dp[i][1]的情况, 依然可以由两个状态推出来
219+
// 第i-1天就不持有股票,那么就保持现状,所得现金就是昨天不持有股票的所得现金 即:dp[i - 1][1]
220+
// 第i天卖出股票,所得现金就是按照今天股票佳价格卖出后所得现金即:prices[i] + dp[i - 1][0]
221+
dp[i][1]=Math.max(dp[i-1][1], dp[i-1][0]+ prices[i]);
222+
}
223+
224+
return dp[prices.length-1][0];
225+
};
226+
```
204227

205228

206229

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp