Help me in solving REDONE problem

My issue

M=1000000007
for _ in range(int(input())):
n=int(input())
a=list(range(1,n+1))
for i in range(n-1):
small=min(a)
large=max(a)
value=small+large+(small*large)
a.remove(small)
a.remove(large)
a.append(value)
b=int(*a)%M
print(b)
I am getting a partially correct answer for this approach
please help me finding correct approach

My code

# cook your dish here
M=1000000007
for _ in range(int(input())):
    n=int(input())
    a=list(range(1,n+1))
    for i in range(n-1):
        small=min(a)
        large=max(a)
        value=small+large+(small*large)
        a.remove(small)
        a.remove(large)
        a.append(value)
    b=int(*a)%M
    print(b)

Problem Link: REDONE Problem - CodeChef

@narayansharma
plzz refer the followinf solution for better understanding of the optimal logic.
your brute force solution will give tle for larger test cases.

# cook your dish here
mod=(10**9)+7
l=[0]
for _ in range(int(input())):
    n=int(input())
    for i in range(len(l),n+1):
        l.append(((l[i - 1] * (i + 1)) + i) % mod)
    print(l[n])

Thanks for helping