← Back to libraryQuestion 120 of 273
⌨️Java CodingIntermediate

House Robber (Max Non-Adjacent Sum)

📌 Definition:

Given an array of non-negative numbers, find the maximum sum you can take without choosing two adjacent elements (e.g. [2,7,9,3,1] -> 12 = 2+9+1).

📖 Detailed Explanation:

At each element you either skip it (keep the best-so-far) or take it plus the best from two positions back: curr = max(prev, prevPrev + x). Track just two rolling values for O(n) time, O(1) space. Greedily taking the largest values can violate the adjacency rule.

💻 Solutions:
public static int rob(int[] a) {
    int prev = 0, curr = 0;
    for (int x : a) {
        int temp = Math.max(curr, prev + x);
        prev = curr;
        curr = temp;
    }
    return curr;
}
function rob(a) {
  let prev = 0, curr = 0;
  for (const x of a) {
    const temp = Math.max(curr, prev + x);
    prev = curr;
    curr = temp;
  }
  return curr;
}
def rob(a):
    prev = curr = 0
    for x in a:
        prev, curr = curr, max(curr, prev + x)
    return curr
🔑 Key Points:
  • take vs skip: curr = max(prev, prevPrev + x)
  • Two rolling variables — O(1) space
  • Greedy on largest values is wrong
  • O(n) time
🌍 Real-World Example:

The take-or-skip recurrence models scheduling with cooldowns and selecting non-conflicting intervals for maximum value.

🎯 Scenario-Based Interview Question:

A candidate greedily sums the largest non-adjacent-looking values and fails on [2,1,1,2] (returns 3 instead of 4). Why is DP needed?