【LeetCode】198.House Robber

来源:互联网 发布:apache一键安装包 编辑:程序博客网 时间:2024/05/16 01:13

题目:

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

解答:

动态规划问题,设maxV[i]为达到第i家商店所能获得的最大利益,则maxV[i] = max(maxV[i-2] + nums[i] ,maxV[i-1]);

代码:

public class Solution {    public int rob(int[] nums) {int[] maxV = new int[nums.length];if (nums.length == 0)return 0;else if (nums.length == 1) {return nums[0];} else {maxV[0] = nums[0];maxV[1] = Math.max(maxV[0], nums[1]);for (int i = 2; i < nums.length; i++) {maxV[i] = Math.max(maxV[i - 2] + nums[i], maxV[i - 1]);}}return maxV[nums.length-1];}}


0 0
原创粉丝点击