Max Non-Adjacent Sum
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
Find the maximum sum of non-adjacent elements in an array (house robber problem). For each element, decide whether to take it or skip it. If taken, add it to the best sum from two positions back. If skipped, take the best sum from one position back. Use rolling variables.
The recurrence considers skipping the current house (keep prev1) or robbing it (prev2 + nums[i]).
Time complexity is O(n), space complexity is O(1).
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.
