Debug Google KickStart "2022" Round D Maximum Gain Problem using Dynamic Programming Technique

Question:

I was solving the Google KickStart 2022 Round D – Maximum Gain Problem through the Dynamic Programming Technique but I am tired of debugging it.
Here is the link to the question: Maximum Gain Problem
Here is my python code:

#supporting function
def proceedForOneOnly(O, k, gainOne):
    if k==0:
        return 0
    return gainOne + max([proceedForOneOnly(O[1:], k-1, O[0]), proceedForOneOnly(O[:-1], k-1, O[-1])])

#solve
def maxGain(A, B, k, gain):
    #BaseCase
    if k==0:
        return 0
    #Checking if any of the two task-arrays are empty
    if len(B)==0:
        return proceedForOneOnly(A, k-1, gain)
    elif len(A)==0:
        return proceedForOneOnly(B, k-1, gain)
    #if both aren't empty
    return gain + max([maxGain(A[1:], B, k-1, A[0]), maxGain(A[:-1], B, k-1, A[-1]), maxGain(A, B[1:], k-1, B[0]), maxGain(A, B[:-1], k-1, B[-1])])

#taking input and caling maxGain() iteratively
def main():
    n = int(input())
    for i in range(n):
        nA = int(input()); A = list(map((lambda i: int(i)), input().split()))
        nB = int(input()); B = list(map((lambda i: int(i)), input().split()))
        k  = int(input())
        print(f"Case #{1}: {maxGain(A, B, k, 0)}")

main()

The issue is that I am getting the output 22 (which should be 24) and 138 (which should be 148) on the first two test cases which are attached below:

2
3
3 1 2
4
2 8 1 9
5
4
1 100 4 3
6
15 10 12 5 1 10
6

Could someone please help me figure out what’s wrong?

Answers:

I think your loop is running one less time.
However, it’ll still take a lot of time to run but if you could pass k+1 instead of k in the first call in the main that is working for me.
Nice Approach btw.
Will try to improve on this

Answered By: Mohsin Taqvi
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.