Open Brand0n-Zhang opened 3 years ago
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
let len = nums.length - 1
function getMax (n) {
if (n === 0) {
return nums[0]
}
if (n === 1) {
return Math.max(nums[0], nums[1])
}
return Math.max(getMax(n - 1), getMax(n - 2) + nums[n])
}
return getMax(len)
};
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
const len = nums.length;
if (len == 0)
return 0;
const dp = new Array(len + 1);
dp[0] = 0;
dp[1] = nums[0];
for (let i = 2; i <= len; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]);
}
return dp[len];
};
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
const len = nums.length
if(len <= 1) {
return len === 0 ? 0 : nums[0]
}
let dp = new Array(len+1)
dp[0] = 0
dp[1] = nums[0]
for(let i = 2; i <= len; i++) {
dp[i] = Math.max(dp[i-1],nums[i-1] + dp[i -2])
}
return dp[len]
};
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
if (nums === null || nums.length < 1) {
return 0
}
if (nums.length === 1) {
return nums[0]
}
const len = nums.length
const dp = new Array()
dp[0] = nums[0]
dp[1] = Math.max(nums[1], nums[0])
for (let i = 2; i < len; i++) {
dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1])
}
return dp[len - 1]
};
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
function add(arr) {
return arr.reduce(function(prev, curr){
return prev + curr;
});
}
var arr1 = nums.filter((value, index) => {
return index % 2 === 0
})
var arr2 = nums.filter((value, index) => {
return index % 2 === 1
})
var value1 = add(arr1);
var value2 = add(arr2);
return value1 > value2 ? value1: value2
};
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
if(nums.length === 0) return 0
if(nums.length === 1) return nums[0]
let dp = [ nums[0], Math.max(nums[0], nums[1])];
for (let i = 2; i < nums.length; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
};
return dp[dp.length - 1];
};
https://leetcode-cn.com/problems/house-robber/