LeetCode 198 House Robber 打家劫舍

来源:互联网 发布:网络设计学习 编辑:程序博客网 时间:2024/05/15 01:46

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.

思路:a维持打劫前"i-2"家的最大值,b维持打劫前"i-1"家的最大值,则打劫第i家的最大值就是Math.max(a + nums[i], b);

public int rob(int[] nums) {if (nums.length <= 0) return 0;if (nums.length == 1) return nums[0];int a = nums[0], b = Math.max(nums[1], nums[0]);for (int i = 2; i < nums.length; i++) {int tmp = b;b = Math.max(a + nums[i], b);a = tmp;}return b;}



0 0