← DiffPush

House Robber

Standard Bar Dynamic Programming · 1D DP O(n) · O(1)

The Sensor Bay Sweep

A maintenance bot harvests energy cells from a row of sensor bays. Each bay holds a different charge, but the fire code forbids opening two neighboring bays in one shift because their shared alarm circuit would trip. The night crew wants the biggest possible haul per shift, so the bot must decide which bays to crack to maximize the collected charge without tripping the alarm.

Input: An array nums of n non-negative integers, where nums[i] is the charge in bay i.

Output: Return the maximum total charge collectable with no two adjacent bays opened.

Constraints

Examples

Example 1

Input: {"nums":[1,2,3,1]}
Output: 4
Bay 0 (1) plus bay 2 (3) — total 4.

Example 2

Input: {"nums":[2,7,9,3,1]}
Output: 12
Bays 0, 2, 4 give 2 + 9 + 1 = 12.

Solve this in your browser →

Also on LeetCode ↗