0
点赞
收藏
分享

微信扫一扫

LeetCode日记 198.打家劫舍

茗越 2023-01-21 阅读 90


题目来源:https://leetcode-cn.com/problems/house-robber/

LeetCode日记 198.打家劫舍_Math


思路:

LeetCode日记 198.打家劫舍_i++_02

class Solution {
public int rob(int[] nums) {
if (nums == null||nums.length == 0){
return 0;
}
if(nums.length == 1){
return nums[0];
}

int pre2 = nums[0];//前n-2间房中能够偷到最多的钱
int pre1 = Math.max(nums[0],nums[1]);//前n-1间房能够偷到最多的钱
//1.偷最后1间房和前n-2间房
//2.偷前n-1间房的钱,最后1间不偷

for(int i = 2;i<nums.length;i++){
int temp = pre1;
pre1 = Math.max(pre2+nums[i],pre1);
pre2 = temp;
}

return pre1;
}
}


举报

相关推荐

0 条评论