您的位置:首页 > 编程语言 > Java开发

LeetCode 198. House Robber(java)

2018-01-20 09:34 337 查看
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.

解法:动态规划解法,每个index的位置有两种选择,rob或者notrob,rob的话可以更新值,notrob可以一直把前面的最大值向后传递,最后返回rob和notrob的最大值即可。时间复杂度为O(n),空间复杂度为O(1)。

public int rob(int[] nums) {
int rob = 0, notrob = 0;
for (int i = 0; i < nums.length; i++) {
int temp = rob;
rob = notrob + nums[i];
notrob = Math.max(temp, notrob);
}
return Math.max(rob, notrob);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode