House robber

Dynamic Programming 1D DP Medium
  • This problem statement is a classic example of the Dynamic Programming technique used often in software development to enhance efficiency
  • In practical terms, it is similar to resource allocation problems where companies try to maximize outputs (like profits, productivity, etc
  • ) without violating some set rules
  • Suppose a company with branches distributed around the world (circular manner) wants to implement a data sync operation
  • To avoid network congestion, the rule is that two adjacent branches can't perform the sync operation simultaneously
  • The solution to our robbery problem can help to schedule these operations to ensure maximum data synchronisation without violating the network rule

A robber is targeting to rob houses from a street. Each house has security measures that alert the police when two adjacent houses are robbed. The houses are arranged in a circular manner, thus the first and last houses are adjacent to each other.


Given an integer array money, where money[i] represents the amount of money that can be looted from the (i+1)th house. Return the maximum amount of money that the robber can loot without alerting the police.

Examples:

Input: money = [2, 1, 4, 9]

Output: 10

Explanation: [2, 1, 4, 9] The underlined houses would give the maximum loot.

Note that we cannot loot the 1st and 4th houses together.

Input: money = [1, 5, 2, 1, 6]

Output: 11

Explanation: [1, 5, 2, 1, 6] The underlined houses would give the maximum loot.

Input: money = [9, 4, 1, 8]

Constraints

  • 1 <= money.length <= 105
  • 0 <= money[i] <= 1000

Hints

  • "Since house 1 and house n are adjacent, we must solve the problem in two separate cases: Exclude the first house and rob from houses [1:n]. Exclude the last house and rob from houses [0:n-1]. This ensures that we never pick both the first and last houses together."
  • "Using dynamic programming (O(n)), we store the results in a dp[] array to avoid redundant calculations. Further optimization reduces space complexity from O(n) to O(1), by storing only the last two computed values."

Company Tags

American Express Docker OYO Rooms Lyft Walmart Wayfair Etsy Goldman Sachs Zoho McKinsey & Company Unity Technologies Electronic Arts Stripe PayPal KPMG Instacart Alibaba Cerner Bungie Riot Games Cloudflare NVIDIA Boston Consulting Group Optum HashiCorp Google Microsoft Amazon Meta Apple Netflix Adobe