LeetCodeの旅(22)-House Robber


タイトル:
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];
        }
    }