[抄题]:
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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.
Example 1:
Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
because they are adjacent houses.
Example 2:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
不知道怎么处理首尾重复的问题:分情况讨论。从0-n-1, 1-n
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[一句话思路]:
exclude必须是用上一次的结果i e,否则会越加越大。所以要把上一次的结果用i e保存起来。
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
分情况讨论也是一种办法。
[复杂度]:Time complexity: O(n) Space complexity: O(1)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
class Solution {
public int rob(int[] nums) {
//corner case
if (nums == null || nums.length == 0) return 0;
if (nums.length == 1) return nums[0]; //discuss in 2 ways
return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1));
} public int rob(int[] nums, int low, int high) {
//define include, exclude
int include = 0; int exclude = 0; //for loop, define i and e, and expand
for (int j = low; j <= high; j++) {
int i = include; int e = exclude;
include = e + nums[j];
exclude = Math.max(i, e);
} //return max
return Math.max(include, exclude);
}
}