Finding largest number we can make
The speed issue can be fixed by using PyPy 3  as it is faster (at least in most codeforces type problems, I don't know in general)

However this will result in a WA verdict. To fix this just modify the break condition as follows and it will work:

if(st!=-1 and x!=int(s[i])):


This is because the current version can sometimes break out of the loop prematurely when \$x == int(s[i])\$ because it may be better to make the segment longer.

Finally, I consider you are using too many flag variables, only one is required. Here is how I would change the code:

n = int(input())
s = input()
f = list(map(int,input().split()))
result = []
flag = 1 
for i in range(len(s)):
    x=f[int(s[i])-1]
    if(x&gt;int(s[i])):
        result.append(str(x)) 
        if(flag==1):
            flag = 0
    else:
        result.append(s[i])
        if(flag!=1 and x!=int(s[i])):
            break
for j in range(i+1,len(s)):
    result.append(s[j])
#print(result)
r = int(''.join(result))
print(r)