How can I retrieve the indices used to generate the max sum such that no adjacent elements are used?

Question:

Below is my code, which produces the indices used, but in some cases, finds a value, and takes the first index containing that value, while I need the specific index from which that value came.

import random

numsLength = random.randint(1,100)
a = [random.randint(0, 400) for i in range(numsLength)]
DP = [[] for i in a]  # This will hold bestSeq from i, initially empty
seq = []
mineNum = []

def solveDP(i):
    global DP

    if i >= len(a):
        return []

    # If this value is already computed return that value
    if len(DP[i]) > 0:
        return DP[i]

    # Include the current element and go to i+2
    arr1 = [a[i]] + solveDP(i + 2)
    # Skip the current element and go to i+1
    arr2 = solveDP(i + 1)
    if sum(arr1) > sum(arr2):
        DP[i] = arr1[:]    # Copy arr1 into DP[i]
    else:
        DP[i] = arr2[:]    # Copy arr2 into DP[i]
    return DP[i]

mines = solveDP(0)
for x in mines: # This loop simply assigns the integers' ordered numbers, in order to track which were used
    if a.index(x) + 1 not in mineNum:
        mineNum.append(a.index(x) + 1)
Asked By: ForgivenProdigy

||

Answers:

Ok, so I think I’ve got it. My solution is simply to include the index i along with a[i] when picking an element. The hack needed is in using sum() to recreate the value you are calculating.

import random

numsLength = random.randint(1,100)
print(numsLength)
a = [random.randint(0, 400) for i in range(numsLength)]
DP = [[] for i in a]  # This will hold bestSeq from i, initially empty

def solveDP(i):
    if i >= len(a):
        return []

    # If this value is already computed return that value
    if DP[i]:
        return DP[i]

    # Include the current element and go to i+2
    arr1 = [(a[i],i)] + solveDP(i + 2)
    # Skip the current element and go to i+1
    arr2 = solveDP(i + 1)
    if sum(i for i, _ in arr1) > sum(i for i, _ in arr2):
        DP[i] = arr1[:]    # Copy arr1 into DP[i]
    else:
        DP[i] = arr2[:]    # Copy arr2 into DP[i]
    return DP[i]

mines = solveDP(0)

mineNum = []
for x,idx in mines:
    if idx+1 not in mineNum:
        mineNum.append(idx+1)
print(mineNum)

Update:

DPS = [sum(i for i, _ in d) for d in DP]
print(DPS)
print(max(DPS))

However, it seems that your algorithm leaves the max as the first index in DP

Answered By: quamrana
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.