House Robber – Leetcode Solution

In this post, we are going to solve the 198. House Robber problem of Leetcode. This problem 198. House Robber is a Leetcode medium level problem. Let’s see the code, 198. House Robber – Leetcode Solution.

Problem

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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Example 1 :

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 2 :

Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

Now, let’s see the code of 198. House Robber – Leetcode Solution.

House Robber – Leetcode Solution

198. House Robber – Solution in Java

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

198. House Robber – Solution in C++

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size() == 1)return nums[0];
        vector<int> dp(nums.size());
        dp[0] = nums[0];
        dp[1] = max(nums[1],dp[0]);
        
        for(int i=2;i<nums.size();i++){
            int incHouse = dp[i-2] + nums[i];
            int excHouse = dp[i-1];
            dp[i] = max(incHouse,excHouse);
        }
        
        return dp[nums.size() - 1];
    }
};

198. House Robber – Solution in Python

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dp = [0]
        if len(nums) == 0:
            return dp[0]
        dp.append(nums[0])
        for i in range(2,len(nums) + 1):
            dp.append(max(dp[i - 1],dp[i - 2] + nums[i - 1]))
        return dp[len(dp) - 1]

Note: This problem 198. House Robber is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *