Skip to main content

Command Palette

Search for a command to run...

Leetcode 198: House Robber

Published
•2 min read•View as Markdown
Leetcode 198: House Robber
D

I am a Software Engineer currently looking out for jobs around seattle, Washington.

Problem Link - https://leetcode.com/problems/house-robber/

Problem Statement :

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:

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.

For any house where the robber is planning to rob, he can either skip the house or take the money.

  • If he skips the house, then the maximum amount so far will be the amount robbed till the previous house.

  • If he decides to take the money from a house, he has to skip the previous house and take the maximum money before and add it to the current house amount.

int solution(int[] nums) {
    int n = nums.length;
    // base cases
    if(n == 0)
        return 0;
    if(n==1)
        return nums[0];

    int dp[] = new int[n+1];
    dp[0] = 0;
    dp[1] = nums[0];

    for(int i=2; i<=n; i++) {
        dp[i] = Math.max(dp[i-2]+nums[i-1], dp[i-1]);
    }
    return dp[n];
}

Time Complexity - O(n)

Space Complexity - O(n)

Leetcode DP Problems

Part 1 of 3

In this series, I will explain Leetcode DP Questions with their solutions. We will start with Knapsack type DP Problems - 0/1 knapsack and Unbounded Knapsack and then go on to LCS type problems.

Up next

Leetcode 70: Climbing Stairs

The below is a very famous DP problem. You are climbing a staircase that has n steps. You can take the steps either 1 or 2 at a time. Calculate how many distinct ways you can climb to the top of the staircase. Example: for n=1, output = 1 for n=2, ou...

More from this blog

Boolean's Blog

27 posts