mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
@ -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];
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -368,7 +368,32 @@ class Solution:
|
||||
return (val1, val2)
|
||||
```
|
||||
|
||||
Go:
|
||||
JavaScript:
|
||||
|
||||
> 动态规划
|
||||
|
||||
```javascript
|
||||
const rob = root => {
|
||||
// 后序遍历函数
|
||||
const postOrder = node => {
|
||||
// 递归出口
|
||||
if (!node) return [0, 0];
|
||||
// 遍历左子树
|
||||
const left = postOrder(node.left);
|
||||
// 遍历右子树
|
||||
const right = postOrder(node.right);
|
||||
// 不偷当前节点,左右子节点都可以偷或不偷,取最大值
|
||||
const DoNot = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
|
||||
// 偷当前节点,左右子节点只能不偷
|
||||
const Do = node.val + left[0] + right[0];
|
||||
// [不偷,偷]
|
||||
return [DoNot, Do];
|
||||
};
|
||||
const res = postOrder(root);
|
||||
// 返回最大值
|
||||
return Math.max(...res);
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user