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

Commit 8ba775d

Browse files
添加(0122.买卖股票的最佳时机II动态规划.md):增加typescript版本
1 parent 3d1ed65 commit 8ba775d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,42 @@ const maxProfit = (prices) => {
295295
}
296296
```
297297

298+
TypeScript:
299+
300+
> 动态规划
301+
302+
```typescript
303+
function maxProfit(prices: number[]): number {
304+
/**
305+
dp[i][0]: 第i天持有股票
306+
dp[i][1]: 第i天不持有股票
307+
*/
308+
const length: number = prices.length;
309+
if (length === 0) return 0;
310+
const dp: number[][] = new Array(length).fill(0).map(_ => []);
311+
dp[0] = [-prices[0], 0];
312+
for (let i = 1; i < length; i++) {
313+
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
314+
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
315+
}
316+
return dp[length - 1][1];
317+
};
318+
```
319+
320+
> 贪心法
321+
322+
```typescript
323+
function maxProfit(prices: number[]): number {
324+
let resProfit: number = 0;
325+
for (let i = 1, length = prices.length; i < length; i++) {
326+
if (prices[i] > prices[i - 1]) {
327+
resProfit += prices[i] - prices[i - 1];
328+
}
329+
}
330+
return resProfit;
331+
};
332+
```
333+
298334

299335

300336
-----------------------

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /