• + 0 comments

    Python: you need to FIX THE MAIN!

    It should be:

    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        t = int(input().strip())
    
        for _ in range(0, t):
            first_multiple_input = input().rstrip().split()
    
            n = int(first_multiple_input[0])
    
            k = int(first_multiple_input[1])
    
            arr = list(map(int, input().rstrip().split()))
        
            result = unboundedKnapsack(k, arr)
    
            fptr.write(str(result) + '\n')
    
        fptr.close()
    

    Resolution:

    def unboundedKnapsack(k, arr):
        # progressively get responses (DP)
        # k 0 1 2 3 4 5 6
        # 0 0 0 0 0 0 0 0 
        # 2 0 0 2 2 4 4 6    dp[i][j] = max(dp[i-1][j], dp[i][j-i]+i)
        # 3 0 0 2 3 4 5 6    (choosing between not adding anything and
        # 4 0 0 2 3 4 5 6     adding the current N's value to the Nth
        #                     value behind)
        
        # stop searching if k is found. If not, return largest.
        
        # Creating dp table
        dp = [[0 for _ in range(0, k+1)] for _ in range(0, len(arr)+1)]
        options = [0] + arr
        num_ints = len(arr)
        max_val = 0
    
        for i in range(1, num_ints+1):
            for j in range(1, k+1):
                if j < options[i]:
                    # is the current k less than the value of the line?
                    dp[i][j] = dp[i-1][j]
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i][j-options[i]]+options[i])
                if dp[i][j] == k:
                    # found k in DP table
                    return k
                max_val = max(max_val, dp[i][j])
                j += 1
            i += 1
            
        # k is not on DP table, so returning max value found
        return max_val