标签:obb 因此 money line challenge ber sys 状态 tle
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.
Example 1:
Input: [3, 8, 4]
Output: 8
Explanation: Just rob the second house.
Example 2:
Input: [5, 2, 1, 3]
Output: 8
Explanation: Rob the first and the last house.
O(n) time and O(1) memory.
思路:
线性DP题目.
设 dp[i] 表示前i家房子最多收益, 答案是 dp[n], 状态转移方程是
dp[i] = max(dp[i-1], dp[i-2] + A[i-1])
考虑到dp[i]的计算只涉及到dp[i-1]和dp[i-2], 因此可以O(1)空间解决.
public class Solution { /** * @param A: An array of non-negative integers * @return: The maximum amount of money you can rob tonight */ public long houseRobber(int[] A) { int n = A.length; if (n == 0) return 0; long []res = new long[n+1]; res[0] = 0; res[1] = A[0]; for (int i = 2; i <= n; i++) { res[i] = Math.max(res[i-1], res[i-2] + A[i-1]); } return res[n]; } }
O(1) 空间复杂度
public long houseRobber(int[] A) { int n = A.length; if (n == 0) return 0; long []res = new long[2]; res[0] = 0; res[1] = A[0]; for (int i = 2; i <= n; i++) { res[i%3] = Math.max(res[(i-1)%2], res[(i-2)%2] + A[i-1]); } return res[n%2]; }
标签:obb 因此 money line challenge ber sys 状态 tle
原文地址:https://www.cnblogs.com/FLAGyuri/p/12078244.html