[LeetCode] HouseRobber Dynamic Planning

2124 단어 LeetCode
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.
 
사고방식: 이것은 동적 기획의 제목이다. 먼저 동적 방정식 max[i]=Max{max[i-2]+nums[i],max[i-1]}를 열거하고 동적 방정식에 따라 프로그램을 쓴다.
시간 복잡도: O(n)
코드:
    public int rob(int[] nums) {

        if(nums==null || nums.length<1) return 0;

        if(nums.length==1) return nums[0];

        if(nums.length==2) return Math.max(nums[0], nums[1]);

        int [] max=new int[nums.length];

        max[0]=nums[0];

        max[1]=Math.max(nums[0], nums[1]);

        for(int i=2;i<nums.length;i++)

        {

            max[i]=Math.max(max[i-2]+nums[i], max[i-1]);

        }

        return max[nums.length-1];

    }

최적화:
확장:

좋은 웹페이지 즐겨찾기