To solve this problem, we need to select non-adjacent elements from an array such that we maximize the number of elements chosen. If there are multiple subsets with the same maximum number of elements, we then select the subset with the highest sum.
Approach
The problem can be efficiently solved using dynamic programming with two states for each element:
- Not Take: The best result (maximum count and sum) when we do not take the current element.
- Take: The best result when we take the current element (which means we cannot take the previous element).
Transitions:
- For Not Take state at position
i, we take the maximum result from either taking or not taking the previous element (since we are not taking the current element). - For Take state at position
i, we take the result from not taking the previous element and add the current element to it (since we can't take adjacent elements).
We use tuples to represent each state, where each tuple is (count, sum). When comparing two states, we first prioritize the count (higher count is better), and if counts are equal, we prioritize the sum (higher sum is better).
Solution Code
def max_non_adjacent():
arr = list(map(int, input().split()))
if not arr:
print(0)
return
n = len(arr)
if n == 1:
print(arr[0])
return
# Initialize states for the first element
prev_not = (0, 0) # (count, sum) when not taking first element
prev_take = (1, arr[0]) # (count, sum) when taking first element
for i in range(1, n):
# Compute current_not: max of prev_not and prev_take
if prev_not[0] > prev_take[0]:
curr_not = prev_not
elif prev_not[0] < prev_take[0]:
curr_not = prev_take
else:
# Same count, choose the one with higher sum
curr_not = prev_not if prev_not[1] > prev_take[1] else prev_take
# Compute current_take: must not take previous element
curr_take = (prev_not[0] + 1, prev_not[1] + arr[i])
# Update previous states for next iteration
prev_not, prev_take = curr_not, curr_take
# Determine the best result between the last not take and take states
if prev_not[0] > prev_take[0]:
print(prev_not[1])
elif prev_not[0] < prev_take[0]:
print(prev_take[1])
else:
print(max(prev_not[1], prev_take[1]))
max_non_adjacent()
Explanation
- Initialization: We start with the first element, initializing the
prev_notstate (no elements taken, sum 0) andprev_takestate (one element taken, sum equal to the first element). - Iteration: For each subsequent element, we compute the current
not takeandtakestates based on the previous states. - Result: After processing all elements, we compare the final
not takeandtakestates to get the optimal result (maximum count, then maximum sum).
This approach ensures we efficiently compute the desired result with a time complexity of O(n) and space complexity of O(1) (since we only keep track of previous states).)

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