Problem:


Score : 400 points

Problem Statement

An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

2 \leq N \leq 200000

c_i is R or W.

Input

Input is given from Standard Input in the following format:

N
c_{1}c_{2}...c_{N}

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the 1-st and 3-rd stones from the left, resulting in RWWR.

Change the color of the 4-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3



Sample input:
4
WWRR


Sample output:
2

Submission status: Time Limit Exceeded

Solution code:
import math
from math import gcd
INF = float("inf")

import sys
input=sys.stdin.readline
import itertools
from collections import Counter

def main():
    n = int(input())
    c = input()
    ans = INF
    for i in range(n+1):
        w = c[:i].count("W")
        r = c[i:].count("R")
        ans = min(ans, max(w,r))
    print(ans)

if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import numpy as np
n=int(input())
c=input()
d=Counter(c)
wn,rn=Counter(c)["W"], Counter(c)["R"]

MIN=min(wn,rn)
ans=np.full(n+1,200001)

for i in range(MIN):
  w=Counter(c[:i])["W"]
  r=rn-(i-w)
  if w<=r:
    ans[i]=r
  else:
    ans[i]=w
    
l=[i for i in range(n) if ans[i]!=200001]

if l:
  print(np.min(ans))
else:
  print(0)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
C=list(input()) #listにすると文字列が１文字ごとに１要素となる
cnt=0
flag1=False
flag2=True

for i in range(n):
  if C[i]=='W':
    for t in range(1,n-i):
      if C[-t]=='R':
        C[i]='R'
        C[-t]='W'
        cnt+=1
        flag2=False
        break
    if flag2:
      flag1=True
  if flag1:
    break

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
num = int(input())
wr = str(input())


r_num = wr.count("R")
i_counts = [r_num]
rw_count = r_num
wr_count = 0
for i in range(num):
  if wr[i] == "W":
    wr_count += 1
  else:
    rw_count -= 1
  i_count = max(wr_count, rw_count)
  i_counts.append(i_count)

  ans = min(i_counts)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = list(input())
l = 0
r = n-1
c = 0
while l < r:
  for i in range(l, r):
    if s[i] == "W":
      l = i
      break
  else:
    l = r
  for i in range(r, l, -1):
    if s[i] == "R":
      r = i
      break
  else:
    r = l
  if l < r:
    c += 1
print(c)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
#s = str(input())
s = list(input())

count = 0

d = False
c = False

while d == False:
  d = True
  for i in range(n):
    if c == False:
      if s[i] =='W':
        firstw = i
        c = True
    if c == True:
      if s[i] =='R':
        lastr = i
        d = False
  if d == False:
    c = False
    #swap
    s[firstw] = 'R'
    s[lastr] = 'W'
    count += 1
    
print(count)

Submission status: Time Limit Exceeded

Solution code:
input()
a=list(input())
while a[0]=="R":
  del a[0]
  if a==[]:break
b=a.count('R')
print(b-a[:b].count('R'))

Submission status: Time Limit Exceeded

Solution code:
num = int(input())
wr = str(input())

i_counts = []
r_num = wr.count("R")

if r_num == 0:
  ans = 0
else:

  for i in range(r_num):
    w_counts = 0
    r_counts = 0
    for j in range(num):
      if i > j and wr[j] == "W":
        w_counts += 1
      elif i < j and wr[j] == "R":
        r_counts += 1
    i_count = max(w_counts, r_counts)
    i_counts.append(i_count)

  ans = min(i_counts)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
num = int(input())
wr = str(input())

wr_list = list(wr)
i_counts = []
for i in range(num):
  w_counts = 0
  r_counts = 0
  for j in range(num):
    if i > j and wr_list[j] == "W":
      w_counts += 1
    elif i < j and wr_list[j] == "R":
      r_counts += 1
  i_count = max(w_counts, r_counts)
  i_counts.append(i_count)

ans = min(i_counts)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N=int(input()) 
c=input()

#print(c.count('R'),c.count('W'))

ANS=np.zeros(N+1)

ANS[0]=c.count('R')
ANS[N]=c.count('W')

for i in range(1,N):
  ANS[i]=max(c[0:i].count('W'),c[i:N].count('R'))

print(int(min(ANS)))

Submission status: Time Limit Exceeded

Solution code:
# alter altar
# WRとなっては行けない
# all W or all R 
# RRRRRWWWWWW 左にR、右にWを集める
length = int(input())
stone = input()
mini = 200000
for sep in range(length+1):
	red = 0
	white = 0
	for left in range(0, sep):
		# print(left, end="")
		if(stone[left] == "W"):
			white += 1
	for right in range(sep, length):
		# print(right, end="")
		if(stone[right] == "R"):
			red += 1
	# print(white)
	# print(red)
	trial = max(white, red)
	mini = min(mini, trial)
print(mini)

Submission status: Time Limit Exceeded

Solution code:
a = int(input())
ar = input()
m = 200000
for i in range(1,a+1):
    b = ar[0:i]
    c = ar[i:a]
    if max(b.count('W'),c.count("R")) < m:
        m = max(b.count('W'),c.count("R"))
print(m)

Submission status: Time Limit Exceeded

Solution code:
def f(s, n, m):
    w_count = s.count('W')
    r_count = s.count('R')
    m = min(w_count, r_count)

    if s.find('WR') == -1:
        return n
    elif n > m:
        return m
    else:
        i, j = 0, -1
        while True:
            if s[j] == 'R':
                break
            else:
                j -= 1

        while True:
            if s[i] == 'W':
                break
            else:
                i += 1

        s = list(s)
        s[i] = 'R'
        s[j] = 'W'
        s = ''.join(s)

        return f(s, n+1, m)

N = int(input())
s = input()
print(f(s, 0, 0))

Submission status: Time Limit Exceeded

Solution code:
a = int(input())
ar = list(input())
m = 200000
for i in range(1,a+1):
    b = ar[0:i]
    c = ar[i:a]
    if max(b.count('W'),c.count("R")) < m:
        m = max(b.count('W'),c.count("R"))
print(m)

Submission status: Time Limit Exceeded

Solution code:
def dfs(s, n, m):
    if n > m:
        return m
    elif s.find('WR') == -1:
        return n
    else:
        w_count = s.count('W')
        r_count = s.count('R')
        m = min(w_count, r_count)

        i, j = 0, -1
        while True:
            if s[j] == 'R':
                break
            else:
                j -= 1

        while True:
            if s[i] == 'W':
                break
            else:
                i += 1

        s = list(s)
        s[i] = 'R'
        s[j] = 'W'
        s = ''.join(s)
        return min(dfs(s, n+1, m), m)

N = int(input())
s = input()
print(dfs(s, 0, len(s)))

Submission status: Time Limit Exceeded

Solution code:
def dfs(s, n):
    if s.find('WR') == -1:
        return n
    else:
        w_count = s.count('W')
        r_count = s.count('R')
        m = min(w_count, r_count)

        i, j = 0, -1
        while True:
            if s[j] == 'R':
                break
            else:
                j -= 1

        while True:
            if s[i] == 'W':
                break
            else:
                i += 1

        s = list(s)
        s[i] = 'R'
        s[j] = 'W'
        s = ''.join(s)
        return min(dfs(s, n+1), m)

N = int(input())
s = input()
print(dfs(s, 0))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
c = list(c)
arr = []
for i in range(n + 1):
  a =  c[:i].count('W')
  b = c[i:].count('R')
  arr.append(max(a, b))
ans = min(arr)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
arr = []
for i in range(n + 1):
  a =  c[:i].count('W')
  b = c[i:].count('R')
  arr.append(max(a, b))
ans = min(arr)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
l = [i for i in input()]
numR = l.count('R')
cnt = 0

if numR == len(l) or numR == 0:
    print(0)
    exit()

for i in range(N):
    if l[-(i + 1)] == 'R':
        cnt += 1
        l[l.index('W')] = 'R'
        l[-(i + 1)] = 'W'
    if l.index('W') == numR:
        print(cnt)
        break

Submission status: Time Limit Exceeded

Solution code:
N = input()                                                                                         
# c = list(map(int, input().split()))                                                               
c = input()                                                                                         
                                                                                                    
N = int(N)                                                                                          
                                                                                                    
dp = []                                                                                             
                                                                                                    
n_w = c.count('W')                                                                                  
n_r = c.count('R')                                                                                  
                                                                                                    
for i in range(N + 1):                                                                                  
    left_w = c[:i].count('W')                                                                       
    right_r = n_r - (i - left_w)                                                                         
    dp.append(max(left_w, right_r))                                                                 
                                                                                                    
print(min(dp))

Submission status: Time Limit Exceeded

Solution code:
N = input()                                                                                         
c = input()

N = int(N)                                                                                          
                                                                                                    
dp = []                                                                                             
                                                                                                    
for i in range(N + 1):                                                                                  
    dp.append(max(c[:i].count('W'), c[i:].count('R')))                                              
                                                                                                    
print(min(dp))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = input()
C = []
for c_i in c:
    C.append(c_i)
count = 0
left = N - 1
for i in range(N):
    if i >= left:
        print(count)
        break
    if C[i] == 'W':
        for j in reversed(range(N)):
            if i == 1:
                if j == i:
                    C[i] = 'R'
                    left = i
                    break
            else:
                if j == i-1:
                    left = i
                    break
            if C[j] == 'R':
                C[i] = 'R'
                C[j] = 'W'
                left = j
                count += 1
                break

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
n=int(input())
c=input()
d=Counter(c)
wn,rn=Counter(c)["W"], Counter(c)["R"]

MIN=min(wn,rn)
ans=[]

for i in range(MIN):
  w=Counter(c[:i])["W"]
  r=rn-(i-w)
  if w<=r:
    ans.append(r)
  else:
    ans.append(w)

if ans:
  print(min(ans))
else:
  print(0)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
n=int(input())
c=input()
d=Counter(c)
MIN=min(Counter(c)["W"],Counter(c)["R"])
ans=[]

for i in range(MIN):
  w=Counter(c[:i])["W"]
  r=Counter(c[i:])["R"]
  if w<=r:
    ans.append(r)
  else:
    ans.append(w)

if ans:
  print(min(ans))
else:
  print(0)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = list(input())
n = 0
for i in range(N):
    if c[i] == 'W':
        for j in range(N - 1, i, -1):
            if c[j] == 'R':
                n += 1
                c[i] = 'R'
                c[j] = 'W'
                break
print(n)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())

c=list(input())


#c[1]=c[2]
sta=1
ans=0
for i in range(N):
    if(-sta+N<i):
        break
    if(c[i]=='W'):
        for j in range(sta,N):
            if(-j+N<=i):
                break
            if(c[-j]=='R'):
                temp=c[-j]
                c[-j]=c[i]
                c[i]=temp
                sta=j
                ans=ans+1
                break


print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())

c=list(input())


#c[1]=c[2]
sta=1
ans=0
for i in range(N):
    if(c[i]=='W'):
        for j in range(sta,N):
            if(-j+N<=i):
                break
            if(c[-j]=='R'):
                temp=c[-j]
                c[-j]=c[i]
                c[i]=temp
                sta=j
                ans=ans+1
                break


print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
s = input()

times = len(s)
for i in range(len(s) + 1):
    r, l = s[:i], s[i:]
    if times > max(r.count("W"), l.count("R")):
        times = max(r.count("W"), l.count("R"))
print(times)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())#ciが R のとき赤、W のとき白
count = n
a = 0
b = 0
# a: R->W, b: W->Rの回数
for i in range(n+1):
  if i == 0:
    a = c.count("R")
    ans = max(a, b)
    count = min(ans, count)
  else:
    a = a - c[0:i].count("R")
    b = b + c[0:i].count("W")
    ans = max(a, b)
    count = min(ans, count)
print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())#ciが R のとき赤、W のとき白
count = n
a = 0
b = 0
 
for i in range(n):
  if i == 0:
    ans = c.count("R")
    count = min(ans, count)
  elif i == n-1:
    ans = c.count("W")
    count = min(ans, count)
  else:
    a = c[0:i].count("W")
    b = c[i:].count("R")
    ans = max(a, b)
    count = min(ans, count)
print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()

ans = n
for i in range(n+1):
    a = c[:i].count("W")
    b = c[i:].count("R")
    ans = min(ans,max(a,b))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
min_count = n
for i in range(n):
    s = c.count('R')
    W = c[:s].count('W')
    R = c[s:].count('R')
    """
    if W <= R:
        count = R # W + (R - W) # 仕切りより左側の白い石W個と、右側に残った赤い石R-W個
    else: # W >R
        count = W # R + (W - R)
    # 結局のところ、count = max(W,R)
    """
    count = max(W,R)        
    if min_count > count:
        min_count = count   
print(min_count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

stone = input()

count = 0
w = n-1
r = 0

for k in range(n):
    for i in range(n):
        if stone[i] == "W":
            w = i
            break

    for i in range(n):
        if stone[n-1-i] == "R":
            r = n-1-i
            break
    #print (w,r,count)
    if w < r:
        stone=stone[:w] + "R" +stone[w+1:r]+ "W" +stone[r+1:]  
        count += 1
        #print(stone)
        
    else:
        break
print (count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
cn = input()
cn = list(cn)

# 入れ替えられるなら入れ替える、無理ならRに変える
ws = [i for i, c in enumerate(cn) if cn[i] == 'W']
ws = set(ws)

#print(cn)
cnt = 0
for i in range(1, len(cn)):
    ri = len(cn) - i
    c = cn[ri]
    if c == 'R':
        if len(ws) > 0:
            # 入れ替える
            j = min(ws)
            if j < ri:
                ws.remove(j)
                ws.add(ri)
                cn[j], cn[ri] = 'RW'
                cnt += 1
                #print('swap')
    else:
        if len(ws) == 0:
            # 色を変える
            cnt += 1
            cn[ri] = 'R'
            ws.remove(ri)
            #print('change')
    #print(i, cn)
    #print(ws)

#print(cn)
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

stone = input()

count = 0
w = n-1
r = 0

for k in range(n):
    for i in range(n):
        if stone[i] == "W":
            w = i
            break

    for i in range(n):
        if stone[n-1-i] == "R":
            r = n-1-i
            break
    #print (w,r,count)
    if w < r:
        stone=stone[:w] + "R" +stone[w+1:r]+ "W" +stone[r+1:]  
        count += 1
        #print(stone)
        
    else:
        break
print (count)

Submission status: Time Limit Exceeded

Solution code:
n = input()
m = input()
wcount = 0
rcount = 0
for i in m:
    if i == "W":
        wcount += 1
    else:
        rcount += 1
new_m = "R"*rcount + "W"*wcount
r_l = []
w_l = []
for i in range(len(m)):
    if m[i] == "W":
        w_l.append(i)
    else:
        r_l.append(i)
m = list(m)
new_m = list(new_m)
count = 0
while m != new_m:
    m[w_l[0]],m[r_l[-1]] = m[r_l[-1]],m[w_l[0]]
    w_l.pop(0)
    r_l.pop(-1)
    count += 1

print(count)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
c=input()
list=[0 for i in range(n+1)]
for i in range(n+1):
  if i>0 and i<n:
    r=c.count('R',i,)
    w=c.count('W',0,i)
  if i==0:
    r=c.count('R',i,)
    w=0
  if i==n:
    r=0
    w=c.count('W')


  if r<=w:
    list[i]=w
  else:
    list[i]=r
print(min(list))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
c = [char for char in c]

r_idx, w_idx = [], []
for j in range(n):
    if c[j] == "R":
        r_idx.append(j)
    elif c[j] == "W":
        w_idx.append(j)

ans = 0
for i in range(len(c) - len(w_idx)):
    if i in w_idx:
        ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)
read = sys.stdin.read
readlines = sys.stdin.readlines
from math import ceil
def main():
    n = int(input())
    a = input()
    if not 'WR' in a:
        print(0)
        sys.exit()
    a = list(a)
    r = 0
    rnum = a.count('R')
    while True:
        if 'W' in a[:rnum]:
            t1 = a[:rnum].index('W')
            t2 = a[rnum:].index('R')
            a[t1] = 'R'
            a[t2+rnum] = 'W'
            r += 1
        else:
            break
    print(r)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import re
import sys

n = int(input())
c = list(input())

count_r = 0
for i in c:
    if i == 'R':
        count_r += 1
count_w = n - count_r
ans = min(count_r, count_w)
if ans == 0:
    print(0)
    sys.exit()

pattern = r"^R*W*$"
# print(re.fullmatch(pattern, "RRRWW"))
# print(re.search(pattern, "RRRWW"))
l = 0
r = n-1
count = 0
while not re.match(pattern, ''.join(c)):
# while l < r:
    while c[l] == 'R':
        l += 1
    while c[r] =='W':
        r -= 1
    c[l] = 'R'
    c[r] = 'W'
    count += 1
    # print(c, l, r)
    # if l == r-1:
    #     break

ans = min(count, ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = [0 if x=='W' else 1 for x in input() ]
cnt = 0
while (0 in c) and (1 in c[c.index(0):]):
  c[-(c[::-1].index(1)+1)] = 0
  c[c.index(0)] = 1
  cnt += 1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
ans = min(c.count('W'),c.count('R'))
for i in range(1, n - 1):
  l = c[:i].count('W')
  r = c[i:].count('R')
  ans = min(ans,max(l,r))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
part = 0
leftW = 0
rightR = S.count('R')
moves = [rightR]

for i in range(N):
	leftW = S[:i+1].count('W')
	rightR = S[i+1:].count('R')
	moves.append(max(leftW, rightR))
# print(moves)
ans = min(moves[i] for i in range(N+1))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys,math,copy
input = sys.stdin.readline

n = int(input())
C = list(input())
for i in range(n):
  if C[i]=='W':
    C[i]=0
  else:
    C[i]=1

#print(C)

ans = 200001

for i in range(n+1):
  D = copy.deepcopy(C)
  LEFT = D[:i]
  RIGHT = D[i:]
  #print(LEFT)
  #print(RIGHT)
  left_err= i - LEFT.count(1)
  right_err= (n-i) - RIGHT.count(0)
  #print(left_err)
  #print(right_err)
  
  a = max(left_err,right_err)
  ans = min(ans, a)
  #print("ans=" + str(ans))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math as mt
import sys, string
from collections import Counter, defaultdict
input = sys.stdin.readline

MOD = 1000000007

I = lambda : int(input())
S = lambda : input()
M = lambda : map(int, input().split())
Ms = lambda : map(str, input().split()) 
ARR = lambda : list(map(int, input().split()))

def main():
    n = I()
    s = S()
    new_s = ""
    for i in range(n):
        if s[i] == 'R':
            new_s += 'R'
    len2 = len(new_s)
    for i in range(n - len2):
        new_s += "W"
    
    ans = 0
    for i in range(n):
        if s[i] != new_s[i]:
            ans += 1
    
    print(ans//2)


# testcases
tc = 1
for _ in range(tc):
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
cnt = 0

while c.count('WR')>=1:
  w = c.index('W')
  r = c[::-1].index('RW')+1
  r *= -1
  cl = list(c)
  cl[w] = 'R'
  cl[r] = 'W'
  c = ''.join(cl)
  cnt += 1

wr = min(c.count('W'),c.count('R'))
cnt = min(cnt,wr)
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
c = [char for char in c]

def op1(l, id1, id2):
    temp = l[id1]
    l[id1] = l[id2]
    l[id2] = temp
    return l

r_idx, w_idx = [], []
for j in range(n):
    if c[j] == "R":
        r_idx.append(j)
    elif c[j] == "W":
        w_idx.append(j)

ans = 0
for i in range(min(len(r_idx), len(w_idx))):
    c = op1(c, w_idx[i], r_idx[-i - 1])
    ans += 1
    if not "W" in "".join(c).rstrip("W"):
        break
if "W" in "".join(c).rstrip("W"):
    ans += "".join(c).rstrip("W").count("W")
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
c=input()
ans=[]
for i in range(N+1):
    ans.append(max(c[i:].count('R'),c[:i].count('W')))
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
c=input()
ans=len(c)
for i in range(N+1):
    ans=min(ans,max(c[i:].count('R'),c[:i].count('W')))
print(ans)

Submission status: Time Limit Exceeded

Solution code:


N = int(input())
red_index_list = []
n_red = 0
c_list = list(input())
for i in range(N):
    if (c_list[i] == 'R'):
        red_index_list.append(i)
        n_red += 1

toku = 0
for i, red_index in enumerate(red_index_list):
    if i==0:
        space = red_index
    else:
        space = red_index - red_index_list[i-1] - 1

    n_right_red = len(red_index_list[i+1:])
    diff = n_right_red - space
    if diff >= 0:
        toku += 1
        for _ in range(space):
            red_index_list.pop(-1)

        if red_index_list[-1] == red_index:
            break
    else:
        break

print(n_red-toku)

Submission status: Time Limit Exceeded

Solution code:
def func_rfindr(str):
    return str.rfind('R')

def func_lfindw(str):
    return str.find('W')

def func_replace(target, pos, str):
    ret = ""
    if pos != 0:
        ret = target[0:pos]
    ret = ret + str
    if len(target) - 1 != pos:
        ret = ret + target[pos + 1:]
    return ret

N = int(input())
C = input()
ans = 0

posrr = func_rfindr(C)
poslw = func_lfindw(C)

while poslw != -1 and posrr != -1 and posrr > poslw:
    C = func_replace(C, posrr, "W")
    C = func_replace(C, poslw, "R")
    ans = ans + 1
    posrr = func_rfindr(C)
    poslw = func_lfindw(C)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# /usr/bin/python3
# -*- coding: utf-8 -*-
from queue import Queue
from queue import LifoQueue as Stack
from math import sqrt, floor, ceil, log2, log10, pi
from fractions import gcd
from itertools import permutations, combinations
from operator import itemgetter
from functools import cmp_to_key


INF=1001001001
__MOD__=(10**9)+7
yn = 'YNeos'
judge = False
cnt = 0
ans = None


def lcm(a, b):
    return (a*b) // gcd(a,b)

def intinput():
    return int(input())

def mulinputs():
    return map(int,input().split())

def lineinputs(func=intinput):
    datas = []
    while True:
        try:
            datas.append(func())
        except EOFError:
            break
    return datas

class ModInt():
    def __init__(self, x):
        self.__x = (x % __MOD__)
    def __add__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x + other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x + other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __radd__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x + self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x + self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __sub__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x - other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x - other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rsub__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x - self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x - self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __mul__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x * other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x * other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rmul__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x * self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x * self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __truediv__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x * other.__modinv())%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x * other.__modinv())%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rtruediv__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x * self.__modinv())%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x * self.__modinv())%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __pow__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__(pow(self.__x, other.__x, __MOD__)))
        elif type(other) == ModInt:
            return self.__class__(pow(self.__x, other.__x, __MOD__))
        else:
            raise Exception("Not Int or Not ModInt")
    def __rpow__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__(pow(other.__x, self.__x, __MOD__)))
        elif type(other) == ModInt:
            return self.__class__(pow(other.__x, self.__x, __MOD__))
        else:
            raise Exception("Not Int or Not ModInt")

    def __modinv(self, m=__MOD__):
        a = self.__x
        if a == 0:
            raise ZeroDivisionError()
        if gcd(a, m) != 1:
            raise Exception("%sの逆数は求まりません。" % a)
        b, u, v = m, 1, 0
        while b != 0:
            t = a//b;
            a -= t*b
            a, b = b, a
            u -= t * v
            u, v = v, u
        u %= m
        if u < 0:
            u += m
        return u
    def __int__(self):
        return self.__x
    def __str__(self):
        return str(self.__x)



if __name__ == '__main__':
    N = intinput()
    S = input()
    S = [c for c in S]
    right = len(S)-1
    r,w = 0, 0
    for i in range(len(S)-1,-1,-1):
        if S[i] == 'R':
            right = i
            r+=1
            break
    left = 0
    for i in range(len(S)):
        if S[i] == 'W':
            left=i
            w+=1
            break

    cnt = 0
    while left <= right:
        cnt += 1
        tmp = S[left]
        S[left] = S[right]
        S[right] = tmp
        for i in range(right-1,0,-1):
            if S[i] == 'R':
                right = i
                r+=1
                break
        for j in range(left, len(S)):
            if S[j] == 'W':
                left = j
                w+=1
                break

    # 出力
    print(cnt)

Submission status: Time Limit Exceeded

Solution code:
input()
s = input()

def find_cost(s):
    counter, i, j = 0, 0, len(s)-1
    while i < j:
        while i < len(s) and s[i] != 'W':
                i += 1
        while j >= 0 and s[j] != 'R':
                j -= 1
        if i < j:
            s = list(s)
            s[i], s[j] = s[j], s[i]
            s = "".join(s)
            counter += 1
        i += 1
        j -= 1

    # print(counter)

    for i in range(0, len(s) - 2):
        if s[i] == 'W' and s[i + 1] == 'R':
            counter += 1

    print(counter)


find_cost(s)

Submission status: Time Limit Exceeded

Solution code:
import math
N= int(input())
c=list(str(input()))
#N=4
#c=['W', 'W', 'R', 'R']
#c.reverse()
#print(c)


num=0
for i in reversed(range(N)):
    if c[i]=='R' :
        for u in (range(num,i)):
            if c[u]=='W':
                c[u]='y'
                c[i]='W'
                num+=1
                break
            
#print(c)
print(num)

Submission status: Time Limit Exceeded

Solution code:
import re
N = int(input())
C = input()
wLen = len(C.replace('R', ''))
rLen = len(C.replace('W', ''))
if wLen == 0 or rLen == 0:
  print(0)

else:
  tmp = C
  res = min(wLen, rLen)
  for i in range(res):
    tmp = re.sub('^R*', '', tmp)
    tmp = re.sub('W*$', '', tmp)
    if len(tmp) == 0:
      res = min(res, i)
      break
    tmp = tmp[1: -1]
    if len(tmp) == 0:
      res = min(res, i + 1)
      break
  print(res)