To solve this problem, we need to find the maximum sum of values from a subset of people such that no two people in the subset are adjacent. This is a classic dynamic programming problem, often referred to as the "House Robber" problem.
Approach
The key insight here is to use dynamic programming with space optimization. We can track two states for each person:
- Take: The maximum sum if we take the current person's value.
- Not Take: The maximum sum if we do not take the current person's value.
Dynamic Programming States:
- Take[i]: Maximum sum up to the i-th person if we take their value. This means we cannot take the (i-1)-th person, so it equals
Not Take[i-1] + a[i]. - Not Take[i]: Maximum sum up to the i-th person if we do not take their value. This is the maximum of taking or not taking the (i-1)-th person, so it equals
max(Take[i-1], Not Take[i-1]).
Space Optimization:
Instead of storing an array for Take and Not Take, we use two variables (take_prev and not_take_prev) to keep track of the previous state values. This reduces the space complexity to O(1).
Solution Code
n = int(input())
a = list(map(int, input().split()))
if n == 0:
print(0)
elif n == 1:
print(max(a[0], 0))
else:
take_prev = a[0]
not_take_prev = 0
for num in a[1:]:
current_take = not_take_prev + num
current_not_take = max(take_prev, not_take_prev)
take_prev, not_take_prev = current_take, current_not_take
print(max(take_prev, not_take_prev))
Explanation
-
Initialization:
- For the first person,
take_previs their value (since taking them is an option), andnot_take_previs 0 (since not taking them gives a sum of 0).
- For the first person,
-
Iterate Over Remaining People:
- For each subsequent person, compute
current_take(sum if we take this person) andcurrent_not_take(sum if we don't take this person). - Update
take_prevandnot_take_prevto the current values for the next iteration.
- For each subsequent person, compute
-
Result:
- The maximum sum is the maximum of
take_prev(sum if we take the last person) andnot_take_prev(sum if we don't take the last person). This handles all cases, including the empty subset (sum of 0).
- The maximum sum is the maximum of
This approach runs in O(n) time complexity (since we iterate over all people once) and O(1) space complexity (using only two variables for state tracking). It efficiently handles all edge cases, including negative values and empty subsets.


作者声明:本文包含人工智能生成内容。