Start learning free

LESSON 371 OF 438 · DYNAMIC PROGRAMMING

House Robber in Java

Practice O(n)

You are a robber planning to rob houses along a street. Each house has some money stashed, given in an array nums: house i holds nums[i].

Neighboring houses share a security system: if two adjacent houses are robbed on the same night, the police are alerted. Return the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: nums = [1, 2, 3, 1]
Output: 4
Explanation: Rob house 0 (money 1) and house 2 (money 3): 1 + 3 = 4.

Example 2:

Input: nums = [2, 7, 9, 3, 1]
Output: 12
Explanation: Rob houses 0, 2 and 4: 2 + 9 + 1 = 12.

Example 3:

Input: nums = [2, 1, 1, 2]
Output: 4
Explanation: Rob house 0 and house 3: 2 + 2 = 4. Skipping two houses in a row can pay off: robbing every other house gives only 3.

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

STEP 1 OF 6
    Ctrl + Enter to check

    House Robber in Java

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free