This problem asks for the largest sum you can build from an array when you are not allowed to pick two neighboring elements. Once you take a value at one index, the values directly next to it can no longer be used.
That restriction is what makes the problem interesting. A number might look attractive by itself, but taking it may block a better combination later. So the real question is not just whether a single value is large. It is whether taking it leads to a better total than skipping it.
For example, if nums = [1,2,3,1], the best result is 4 by taking 1 and 3. If nums = [2,7,9,3,1], the answer is 12 from 2 + 9 + 1. In nums = [5,1,1,5], taking both end values gives 10, which is better than any choice involving adjacent numbers.
So the task is to decide, for each position, whether it is better to include that value and skip its neighbor or ignore it and keep the best total found so far, then return the maximum total at the end.
Example Input & Output
Choose 1 (index 0) and 3 (index 2) for a total of 4.
One optimal choice is 2 (index 0), 9 (index 2), and 1 (index 4) for a total of 12.
Choose 5 (index 0) and 5 (index 3) for a total of 10.
Algorithm Flow

Solution Approach
A good way to solve this problem is with dynamic programming using two running totals. At each number, we choose between two options: skip the current value and keep the best total so far, or take the current value and add it to the best total from two positions back.
This works because the restriction only cares about adjacency. If we take nums[i], then the best total we can combine with it is the best answer up to i - 2. If we skip nums[i], then the answer stays whatever was best up to i - 1.
We can store those two states in two variables:
Here, prevTwo means the best total up to two positions ago, and prevOne means the best total up to the previous position.
Then we process each number and build the new best answer:
prevOne handles the skip case, and prevTwo + num handles the take case. Taking the larger of the two gives the best answer up to the current index.
After the loop, prevOne is the maximum sum with no adjacent selections:
This runs in O(n) time and uses O(1) extra space.
Best Answers
class Solution {
public int rob(Object nums) {
int[] arr = (int[]) nums;
if (arr.length == 0) {
return 0;
}
if (arr.length == 1) {
return arr[0];
}
int prev2 = arr[0];
int prev1 = Math.max(arr[0], arr[1]);
for (int i = 2; i < arr.length; i++) {
int curr = Math.max(prev1, prev2 + arr[i]);
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
