前面写过一道,在一条街道上如何抢劫的最多,这道题是那道题的继承。关键之处在于,前面的那个街道,变成了环形的。
使用java写出DP方程,dp[0] = nums[0], dp[1] = Math.max(nums[0], nums[1])
dp[i] = math.max(dp[i-2] + nums[i], dp[i - 1]),
我是直接写出了一个DPHelper,同样可以解决一条街
public static int robHelper (int[] nums, int lo, int hi) {
int preRob = 0; // simple explain
int preNotRob = 0;
int rob = 0;
int notRob = 0;
for (int j = lo; j <= hi; j++) {
// what is the include and exclude
rob = preNotRob + nums[j];
notRob = Math.max(preRob, preNotRob);
preRob = rob;
preNotRob = notRob;
}
return Math.max(rob, notRob);
}
环形街道的话。
public static int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
if (nums.length == 2) {
return Math.max(nums[0], nums[1]);
}
return Math.max(robHelper(nums, 0, nums.length - 2), robHelper(nums, 1, nums.length - 1));
// this is an extension of House Robber
}