Created
March 26, 2020 15:19
-
-
Save yun77op/7435891c41207660570886b40f194094 to your computer and use it in GitHub Desktop.
给定⼀个整数数组 a,实现⼀个函数 countMax(a) ,计算出从 a 中选择出多个不相邻元素组成最⼤的 和是多少。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Solution(array) { | |
const dp = new Array(array.length); | |
dp[0] = []; | |
dp[0][0] = 0; | |
dp[0][1] = array[0]; | |
let max = 0; | |
for (let i = 1; i < array.length; ++i) { | |
dp[i] = []; | |
dp[i][0] = Math.max(dp[i-1][0], dp[i - 1][1]); | |
dp[i][1] = dp[i-1][0] + array[i]; | |
max = Math.max(max, dp[i][0], dp[i][1]); | |
} | |
return max; | |
} | |
Solution([7, 4, 5, 3]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment