198. 房子盗贼 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.
题意:对一组房子进行盗劫,不能盗劫相邻的房子,求最大收益
解法:使用动态规划求解,维护一个dp数组,递推公式为:Math.Max(dp[i - 1], nums[i] + dp[i - 2]);
public class Solution {
public int Rob(int[] nums) {
if (nums.Length == 0) {
return 0;
} else if (nums.Length == 1) {
return nums[0];
} else if (nums.Length == 2) {
return Math.Max(nums[0], nums[1]);
}
int[] dp = new int[nums.Length];
dp[0] = nums[0];
dp[1] = Math.Max(nums[0], nums[1]);
for (int i = 2; i < nums.Length; i++) {
dp[i] = Math.Max(dp[i - 1], (nums[i] + dp[i - 2]));
}
return dp[nums.Length - 1];
}
}