r/DailyCodingProblem • • Apr 06 '22

Daily Coding Problem: Problem #9 [Hard] - 2022-04-04

Good morning! Here's your coding interview problem for today.

This problem was asked by Airbnb.

Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.

For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.

Follow-up: Can you do this in O(N) time and constant space?

1 Upvotes

1 comment sorted by

View all comments

1

u/T4ll1n Apr 06 '22

I did not manage to get a solution that is working. Here is my attempt.


import numpy as np


def largest_sum(input_list):
    len_il = len(input_list)
    if len_il == 0:
        return None
    if len_il == 1:
        return input_list[0]
    if len_il == 2:
        return max(input_list)

    # transform into a numpy array for easier indexing
    input_array = np.array(input_list)

    # loop in an expanding way over the array, starting at 0 and then going (0,2,4,6, ...), (0,3,6,9, ...), (0, 4, 8, 12, ...)
    non_adjacent_odd = [input_array[range(0, len_il, x)] for x in range(2, len_il)]
    # [array([2, 6, 5]), array([2, 2]), array([2, 5])]
    non_adjacent_even = [input_array[range(1, len_il, x)] for x in range(2, len_il)]
    # [array([4, 2]), array([4, 5]), array([4])]

    max_even = max([np.sum(x) for x in non_adjacent_even])
    # 6
    max_odd = max([np.sum(x) for x in non_adjacent_odd])
    # 10

    return max(max_even, max_odd)


input_list = [2, 4, 6, 2, 5]
assert largest_sum(input_list) == 13
input_list = [5, 1, 1, 5]
assert largest_sum(input_list) == 10
input_list = [5, 1, 9]
assert largest_sum(input_list) == 14

# raises an error, because I do not have to steps from 0, to 2, to 5 in my range iteration.
input_list = [5, 1, 9, 2, 2, 5]
assert largest_sum(input_list) == 19

# googling this problem (as you everyone always does with these kind of problems in the real world) gives the following solution
def comb_no_adj(lst, num, last=False):
    if num == 0:
        yield []
    if 0 < num <= len(lst):
        first, *rest = lst
        if not last:
            for c in comb_no_adj(rest, num-1, True):
                yield [first] + c
        for c in comb_no_adj(rest, num, False):
            yield c

# This is again a solution using some form of iterative function calling itself.
# I have never in my real job needed to write function that calls itself in this way
# or at least not having to implement it myself. M
# Maybe in some other parts of software development that is actually happening frequently?
# For me with statistical modelling, this never was relevant