【动态规划】198. 打家劫舍

☞梦想进大厂的一只程序猿☜

☞期望毕业前力扣刷够400题☜

☞正在复习数据结构和算法☜

☞博客地址:https://www.huangliangshuai.com/

1. 题目描述

在这里插入图片描述

2. 题目分析

  1. 经典的DP问题,也是DP的入门。条件:小偷不能偷相邻的房间
  2. 如果我们当前对于最后一户人家,我们决定偷他:
    那我们获取的最大利益是:nums[i] + opt[i - 2] 这里的opt代表,我们从第一家偷到第几家的收益
    如果我们不偷的话,那我们获取的最大利益是:opt[i - 1]
    我们可以列关系式:opt[i] = Math.max(opt[i-1], nums[i] + opt[i-2]);
  3. 我们需要找到出口,这个题目的出口比较简单,也就是opt[0] = nums[0]、opt[1] = Math.max(nums[0], nums[1]);

3. 题目代码

class Solution {
    public int rob(int[] nums) {
        int[] opt = new int[nums.length];
		if (nums.length == 0) {
			return 0;
		}
		if (nums.length == 1) {
			return nums[0];
		}
		opt[0] = nums[0];
		opt[1] = Math.max(opt[0], nums[1]);
		for (int i = 2; i < nums.length; i++) {
			opt[i] = Math.max(opt[i - 1], nums[i] + opt[i - 2]);
		}
		return opt[nums.length - 1];
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40915439/article/details/107850153
今日推荐