"Largest sum of non-adjacent numbers in a list of integers"

Given a list of integers, the largest sum of non-adjacent numbers can be found by writing a function. The function will take the list as input and return the largest sum possible.

Problem

Given a list of integers, write a function that returns the largest sum of non-adjacent numbers.
Input: [2, 4, 6, 8]
Output: 12

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
def largest_sum(arr):
    if len(arr) <= 2:
        return max(0, max(arr))

    cache = [0 for i in arr]
    cache[0] = max(0, arr[0])
    cache[1] = max(cache[0], arr[1])

    for i in range(2, len(arr)):
        num = arr[i]
        cache[i] = max(num + cache[i - 2], cache[i - 1])
    return cache[-1]

print(largest_sum([2, 4, 6, 8]))

A.I. Evaluation of the Solution

The candidate's solution is correct and solves the problem. The approach is to use a dynamic programming approach, which is a good approach for this problem. The candidate could have been more concise in their solution, but overall the solution is correct and solves the problem.

Evaluated at: 2022-11-19 10:16:09