Leetcode 198: House Robber

Leetcode 198: House Robber

·

2 min read

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)