专业盗贼
const rob = (nums) => {
let masterChallenger = 0;
let signUped = 0;
nums.forEach((item)=>{
const newChallenger = signUped;
signUped = item + masterChallenger;
masterChallenger = Math.max(masterChallenger, newChallenger);
});
return Math.max(masterChallenger, signUped);
}
rob([1, 2, 3])
4
rob([1, 5, 3])
5
rob([1, 12, 3, 2 ,5])
17
思路:先找出最高的,将最高的存起来,然后将其本身和紧邻的两个置0,递归,直到最高的为0
var rob =(function (){
var a=0return function(n){
if(Math.max(...n)==0){
return a
}
a+= Math.max(...n)
let m=n.indexOf( Math.max(...n))
n.splice(m-1,3,0,0,0);
return rob(n)
}
})()
rob([1, 5, 3, 6 ,12,1,3,4,7,2,4,1,7,8,9,421,42,421,11,34,5,6,6765,112,2])//7682