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.spa
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.code
Code: 使用了動態規劃,時間複雜度是O(n^2)blog
public class Solution { public int rob(int[] nums) { int n = nums.length; int[] dp = new int[n]; for (int i = 0; i < dp.length; i++) { dp[i] = Integer.MIN_VALUE; } if (n < 1){ return 0; } dp[n-1]=nums[n-1]; for (int i = n-2; i >=0 ; i--) { for (int j = i; j < n; j++) { dp[i] = Math.max(dp[i], nums[j]+(j+2 >= n ? 0 : dp[j+2])); } } return dp[0]; } }
看了網友提交的答案,瞬間以爲個人腦子秀逗了……排最靠前的代碼以下,時間複雜度爲O(n),速度快了不少it
(看了下,思路不是很清楚,有朋友能解惑麼?慚愧)io
public class Solution { public int rob(int[] nums) { int prevYes = 0; int prevNo = 0; for (int num : nums) { int temp = prevNo; prevNo = Math.max(prevNo, prevYes); prevYes = temp + num; } return Math.max(prevNo, prevYes); } }