Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

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 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.

Dynamic Programming

Code

class Solution {
public:
    int rob(vector<int>& nums)
    {
        int n = nums.size();
        if (n == 1) return nums[0];

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

Reduced space complexity DP.

Code

class Solution {
public:
    int rob(vector<int>& nums){
        if (nums.size() == 0) return 0;

        int prev1 = 0, prev2 = 0;
        for (auto& x : nums) {
            int temp = prev1;
            prev1 = max(prev1, x + prev2);
            prev2 = temp;
        }
        return prev1;
    }
};

MUST READ: