leetcode 198 House Robber

题目详情

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.

题目的意思是,咱们是一个江洋大盗~如今咱们要去偷整条街的房子,每一个房子里有必定的钱。可是任何临近的两个房子被偷就会触发警报。要求咱们求出在不触发警报的状况下偷到的最多的钱。每一个房子里的钱经过输入的int数组表示。数组

想法

  • 动态规划问题
  • 对于每个房子,咱们有偷/不偷两种选择
  • 所以咱们声明两个变量prevNo和prevYes分别保存,我没偷/偷了当前房子的状况下,目前为止偷的最多的钱数。
  • 若是想偷当前房子,那么要求咱们并无偷前一个房子,因此用前一个房子的prevNo值和当前房子的钱数相加。
  • 若是不偷当前房子,那咱们能够取前一个房子的prevNo值和prevYes值中较大的那个。

解法

public int rob(int[] nums) {
                int prevNo = 0;
        int prevYes = 0;
        
        for(int n: nums){
            int temp = prevNo;
            prevNo = Math.max(prevNo, prevYes);
            prevYes = temp+n;
        }
        
        return Math.max(prevNo, prevYes);
    }
相关文章
相关标签/搜索