mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加121.买卖股票的最佳时机-JavaScript版
This commit is contained in:
@ -313,6 +313,26 @@ func max(a,b int)int {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
JavaScript:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const maxProfit = prices => {
|
||||||
|
const len = prices.length;
|
||||||
|
// 创建dp数组
|
||||||
|
const dp = new Array(len).fill([0, 0]);
|
||||||
|
// dp数组初始化
|
||||||
|
dp[0] = [-prices[0], 0];
|
||||||
|
for (let i = 1; i < len; i++) {
|
||||||
|
// 更新dp[i]
|
||||||
|
dp[i] = [
|
||||||
|
Math.max(dp[i - 1][0], -prices[i]),
|
||||||
|
Math.max(dp[i - 1][1], prices[i] + dp[i - 1][0]),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return dp[len - 1][1];
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user