198. House Robber

Hint
class Solution { public: int rob(vector<int>& nums) { // If there's only one house, return the value in that house // Create a DP array to store the maximum amount of money that can be robbed up to each house // Initialize the DP array // The max money that can be robbed from the first house is the value of the first house // The max money from the first two houses is the max value between the two // Fill the DP array using the recurrence relation for () { // The max money that can be robbed up to the i-th house is either: // - the max money robbed up to the (i-1)-th house (i.e., skipping the i-th house), or // - the max money robbed up to the (i-2)-th house plus the value in the i-th house } // The last element in the DP array contains the maximum amount of money that can be robbed from all houses } };
Solution - DP
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); if (n == 1) return nums[0]; vector<int> dp(n); 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.back(); } };
  • T:
    O(N)
  • S:
    O(N)
Solution - DP Improved
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); if (n == 1) return nums[0]; int first = nums[0]; int second = max(nums[0], nums[1]); int curMax = INT_MIN; for (int i = 2; i < n; ++i) { curMax = max(second, first + nums[i]); first = second; second = curMax; } return second; } };
  • T:
    O(N)
  • S:
    O(1)