To solve this problem, we need to find the maximum sum of non-adjacent elements in a sequence of integers. 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 only need to keep track of the maximum sum up to the previous element and the element before that, as we don't need the entire history of sums. This reduces the space complexity to O(1) while maintaining O(n) time complexity.
-
Base Cases:
- If the input list is empty, return 0.
- If the list has only one element, return that element.
- If the list has two elements, return the maximum of the two elements.
-
Recurrence Relation:
- For each element at position
i, we have two choices: take it or not take it.- If we take it, we add it to the maximum sum up to the element before the previous one (since we can't take adjacent elements).
- If we don't take it, the maximum sum remains the same as the maximum sum up to the previous element.
- Thus, the maximum sum at position
iismax(prev_sum, prev_prev_sum + current_element).
- For each element at position
Solution Code
def max_non_adjacent_sum(nums):
if not nums:
return 0
n = len(nums)
if n == 1:
return nums[0]
prev_prev = nums[0]
prev = max(nums[0], nums[1])
for i in range(2, n):
current = max(prev, prev_prev + nums[i])
prev_prev, prev = prev, current
return prev
Explanation
- Initialization: We start with
prev_prevas the first element andprevas the maximum of the first two elements. - Iteration: For each subsequent element, we compute the current maximum sum by choosing the better option between taking the current element (and adding it to
prev_prev) or not taking it (keepingprev). - Result: The final value of
prevgives the maximum sum of non-adjacent elements.
This approach efficiently computes the result with minimal space usage, making it suitable for large input sizes. The time complexity is O(n) because we iterate through the list once, and the space complexity is O(1) since we only use a few variables.
Example:
- Input:
[2,7,9,3,1] - Output:
12(sum of 2 +9 +1)
Another example:
- Input:
[1,2,3,1] - Output:
4(sum of1 +3)
This solution handles all edge cases, including empty lists, single-element lists, and lists with negative numbers. It's optimal and efficient.
Final Answer:
The function max_non_adjacent_sum as defined above will return the desired result. For the problem's context, the code is the correct solution.
def max_non_adjacent_sum(nums):
if not nums:
return 0
n = len(nums)
if n == 1:
return nums[0]
prev_prev = nums[0]
prev = max(nums[0], nums[1])
for i in range(2, n):
current = max(prev, prev_prev + nums[i])
prev_prev, prev = prev, current
return prev


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