leet-code/src/main/java/leetcode/editor/cn/HouseRobber.java
huangge1199@hotmail.com 3445011c87 191:位1的个数
2021-07-19 23:39:34 +08:00

61 lines
1.7 KiB
Java
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上
//被小偷闯入,系统会自动报警。
//
// 给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
//
//
//
// 示例 1
//
//
//输入:[1,2,3,1]
//输出4
//解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
//  偷窃到的最高金额 = 1 + 3 = 4 。
//
// 示例 2
//
//
//输入:[2,7,9,3,1]
//输出12
//解释:偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
//  偷窃到的最高金额 = 2 + 9 + 1 = 12 。
//
//
//
//
// 提示:
//
//
// 1 <= nums.length <= 100
// 0 <= nums[i] <= 400
//
// Related Topics 数组 动态规划
// 👍 1559 👎 0
package leetcode.editor.cn;
//198:打家劫舍
class HouseRobber {
public static void main(String[] args) {
//测试代码
Solution solution = new HouseRobber().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int rob(int[] nums) {
int[] dp = new int[2];
dp[1] = nums[0];
for (int i = 1; i < nums.length; i++) {
int tmp = dp[1];
dp[1] = nums[i] + dp[0];
dp[0] = Math.max(tmp, dp[0]);
}
return Math.max(dp[1], dp[0]);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}