您的位置:首页 > Web前端 > JavaScript

House Robber

2016-06-13 01:32 375 查看
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it
will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Tags

DP

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

We can conclude the rule as:

f
= Math.max(f[n-1], f[n-2]+n);

/**
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
var len = nums.length;
if (len === 0) {
return 0;
}

var f = [];
f[0] = nums[0];
f[1] = Math.max(nums[0], nums[1]);
for (var i = 2; i < len; i++) {
f[i] = Math.max(f[i - 2] + nums[i], f[i - 1]);
}

return f[len - 1];
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息