LeetCode -- 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.


大概意思是要去抢劫经过的马,求所能抢劫的最大值,但是不能连续抢劫两匹马会被报警。


这个题目可以理解为给定1个数组,每次取一个数,不能连续取两个相邻的数字,找出最大值。
是个典型的DP问题。
令 do[0] = 0; dp[1] = max(a[0],0);

得递推公式:
dp[n] = max(dp[n-1], dp[n-2]+a[n]) ; //从上次的最好结果和上上次加这次的结果中取一个最大值


实现代码:





public int Rob(int[] nums) {
        
        if(nums == null || nums.Length == 0){
            return 0;
        }
        var len = nums.Length;
    	var dp = new int[len + 1];
    	dp[0] = 0;
    	dp[1] = Math.Max(nums[0], 0);
    	
    	for(var i = 2;i < len + 1; i++){
    		dp[i] = Math.Max(dp[i-1], dp[i-2] + nums[i-1]);
    	}
	
	    return dp[len];
    }


你可能感兴趣的:(LeetCode,数据结构与算法)