Max Array Sum

  • + 0 comments

    def max_sum_non_adjacent(arr): if not arr: return 0 if len(arr) == 1: return arr[0]

    # Initialize prev2 (max sum until i-2) and prev1 (max sum until i-1)
    prev2 = 0
    prev1 = 0
    
    # Traverse through the array
    for num in arr:
        current = max(prev1, num + prev2)
        prev2 = prev1
        prev1 = current
    
    return prev1