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.算法
題目大意:你是一名專業強盜,計劃沿着一條街打家劫舍。每間房屋都儲存有必定數量的金錢,惟一能阻止你打劫的約束條件就是:因爲房屋之間有安全系統相連,若是同一個晚上有兩間相鄰的房屋被闖入,它們就會自動聯絡警察,所以不能夠打劫相鄰的房屋。數組
給定一列非負整數,表明每間房屋的金錢數,計算出在不驚動警察的前提下一夜最多能夠打劫到的金錢數。
解題思路:動態規劃(Dynamic Programming)
狀態轉移方程:dp[i] = max(dp[i - 2], dp[i - 3]) + num[i] 【A】
其中,dp[i]表示打劫到第i間房屋時累計取得的金錢最大值。
第 i 個位置的 max 值是由 max(i-2, i-3) 加上 i 位置的值決定,以此類推)安全
算法實現類spa
public class Solution { public int rob(int[] nums) { if (nums == null || nums.length == 0) { return 0; } // 若是數組中的元素個個數大於2個,對於【A】式,i=2,dp[2-3]不存在 if (nums.length > 2) { nums[2] += nums[0]; } // 從第四個元素開始處理 int i = 3; for (; i < nums.length; i++) { // 求出第i個元素的最大值 nums[i] += Math.max(nums[i - 2], nums[i - 3]); } // 若是隻有一個元素,返回這個元素值 if (nums.length == 1) { return nums[0]; } // 有兩個元素返回其中較大的值 else if (nums.length == 2) { return Math.max(nums[0], nums[1]); } // 多於兩個元素,最大值在末尾兩個之間,找最大的返回 else { return Math.max(nums[i - 1], nums[i - 2]); } } }