LeetCode之旅(22)-House Robber

时间:2022-12-08 19:07:08

题目:

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【n】的非相邻元素的最大和。
  • 这一类问题要用动态规划的思路,把数组的长度,作为每一步。设置数组count【n】作为数组的每一步的最大的和。存在推倒关系:count【n】 = max(count【n-1】,(count【n-2】+a【n】));

    -

代码:

public class Solution {
    public int rob(int[] nums) {
        int[] count = null;
        int n = nums.length;
        if(n == 0){
            return 0;
        }
        if(n == 1){
            return nums[0];
        }
        if(n > 1){
            count = new int[n];
        }
        count[0] = nums[0];
        if(nums[1] > nums[0]){
            count[1] = nums[1];
        }else{
            count[1] = nums[0];
        }
        for(int i = 2;i < n;i++){
            if((count[i-2]+nums[i]) > count[i-1]){
                count[i] = count[i-2]+nums[i];
            }else{
                count[i] = count[i-1];
            }
        }
        return count[n-1];
    }
}