To solve this problem, we need to find the maximum sum of non-adjacent elements in an array. This is a classic dynamic programming problem where we can optimize both time and space complexity.
Approach
The key insight here is to use dynamic programming with space optimization. Instead of maintaining an entire array to store intermediate results, we only keep track of the last two results (since we only need the previous two values to compute the current value).
The core logic is:
- For each element, we have three choices:
- Not take the current element: The maximum sum remains the same as the previous maximum.
- Take the current element alone: If the previous sums are negative, taking the current element alone might be better.
- Take the current element plus the best sum from two positions back: This ensures we don't take adjacent elements.
- We also consider the option of taking no elements (sum = 0) if all elements are negative.
Solution Code
def max_non_adjacent_sum(arr):
if not arr:
return 0
n = len(arr)
if n == 1:
return max(arr[0], 0) # Allow zero if element is negative
# Initialize the first two values (considering zero as an option)
prev_prev = max(arr[0], 0)
prev = max(arr[0], arr[1], 0)
for i in range(2, n):
# Compute current maximum sum
current = max(prev, arr[i], prev_prev + arr[i], 0)
# Update previous values for next iteration
prev_prev, prev = prev, current
return prev
Explanation
Let’s break down the solution:
- Edge Cases:
- If the array is empty, return 0.
- If the array has one element, return the maximum of that element or zero (to allow taking no elements if the element is negative).
- Initialization:
prev_prev: The maximum sum up to the first element (considering zero).prev: The maximum sum up to the second element (considering zero).
- Iteration:
- For each element from the third position onwards, compute the current maximum sum using the three choices mentioned earlier.
- Update
prev_prevandprevto move forward in the array.
- Result: The final value of
prevgives the maximum sum of non-adjacent elements (including the option of taking no elements if all are negative).
Key Optimizations
- Space Complexity: O(1) (only two variables are used instead of an array).
- Time Complexity: O(n) (we traverse the array once).
This solution efficiently handles all cases, including arrays with negative elements and allows taking no elements if it results in a higher sum (zero). It's optimal and works for large arrays.
Example Test Cases:
- Test Case 1:
arr = [3,2,7,10]→ Output:13(3+10). - Test Case 2:
arr = [-5,-3,-2,-1]→ Output:0(take no elements). - Test Case 3:
arr = [5,5,10,100,10,5]→ Output:110(5+100+5). - Test Case 4:
arr = [-2,1,-3,4,-1,2,1,-5,4]→ Output:10(4+2+4).
All these test cases are handled correctly by the solution.


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