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:
N = int(input())
C = list(input())
num = 0
for i in range(N):
  if C[i] == "W":
    for j in range(N-i-1):
      if C[N-j-1] == "R":
        C[i] = "R"
        C[N-j-1] = "W"
        num += 1
        break
print(num)

Submission status: Time Limit Exceeded

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

num_of_R = S.count('R')


num_of_left_R = S[:num_of_R].count('R')
ans = 0
while num_of_R != num_of_left_R:
    ans = ans + 1
    
    left_white_idx = S.find('W')
    right_red_idx  = S.rfind('R')

    S = S[:left_white_idx] + 'R' + S[left_white_idx+1:]
    S = S[:right_red_idx] + 'W' + S[right_red_idx+1:]

    num_of_left_R = S[:num_of_R].count('R')

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
c=input()
ans=0
def happy(c,n):
    t=0
    for i in range(n-1):
        if c[i+1]!=c[i]:
            t+=1
    if t==1 and c[0]=='R':
        return True
    else:
        return False
arr=[]
for i in c:
    arr.append(i)
allw='W'*n
allr='R'*n
if c==allw or c==allr:
    print(0)
else:
    while happy(arr,n)!=True:
        br=False
        for i in range(n-1):
            if arr[i]=='W':
                for j in range(1,n):
                    if arr[-j]=='R':
                        br=True
                        arr[i]='R'
                        arr[-j]='W'
                        ans+=1
                        break
            if br:
                break
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = str(input())
cn = [False]*n
for i in range(n):
    if c[i]=="R":
        cn[i]= True


ans = 0
k=n-1
b=0

for i in range(n):
    if b==1:
        break

    if cn[i]== False:
        for j in range(k,0,-1):

            if cn[j]==True:
                k =j
                if i < j:
                    cn[i]=True
                    cn[j]=False
                    ans +=1
                    break
                elif i>=j:
                    b=1
                    break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
List=list(S)
flag=True
mid = ""
res = 0
for i in range(N):
  if List[i] == "R":
    pass
  else:
    for j in range(N-1,-1,-1):
      if i == j:
        flag=False
        break
      if List[j] == "R":
        List[i]="R"
        List[j]="W"
        res += 1
        break
  if flag == False:
    break
for i in range(N-1):
  if List[i] == "W" and List[i+1] == "R":
    List[i+1] == "W"
    res +=1
    break
print(res)

Submission status: Time Limit Exceeded

Solution code:
def input_int_list():
    return [int(thing) for thing in input().split(" ")]

def int_input():
    return int(input())


def print_ans(string):
    print(string)
    exit()

def yes():
    print("Yes")
    exit()

def no():
    print("No")
    exit()

def is_ok(string):
    if "WR" in string:
        return False
    else:
        return True

if __name__ == '__main__':
    N =int_input()
    c_string=input()
    i = 0
    while True:
        if is_ok(c_string):
            print_ans(i)
        left_W =c_string.index("W")
        right_R = len(c_string)-c_string[::-1].index("R")
        c_string = c_string[left_W+1:right_R-1]
        i = i+1

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = str(input())
cn = [False]*n
for i in range(n):
    if c[i]=="R":
        cn[i]= True


ans = 0
k=n-1
b=0

for i in range(n):
    if b==1:
        break

    if cn[i]== 0:
        for j in range(k,0,-1):

            if cn[j]==1:
                k =j
                if i < j:
                    cn[i]=1
                    cn[j]=0
                    ans +=1
                    break
                elif i>=j:
                    b=1
                    break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
line = list(input())
if 'W' not in line or 'R' not in line:
    print(0)
else:
    ans = min(line.count('W'),line.count('R'))
    for i in range(n):
        if line[i] == 'R':
            w = line[:i].count('W')
            r = line[i+1:].count('R')
            ans = min(ans,abs(w-r)+min(w,r))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
cs = list(input())

ans = 0
sorted = N - 1
for i in range(N):
  if cs[i] == "W":
    for j in range(sorted, i, -1):
      if cs[j] == "R":
        cs[i], cs[j] = cs[j], cs[i]
        ans += 1
        sorted = j
        break

print(str(ans))

Submission status: Time Limit Exceeded

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

while True:
    if len(c) >= 1 and c[0] == 'R':
        del c[0]
    else:
        N = len(c)
        break

if N <= 1:
    print(0)
else:
    ans = 0
    r = N
    for w in range(N):
        if c[w] == 'R':
            continue
        else:
            while True:
                r += -1
                if r == -1 or c[r] == 'R':
                    break
            if r < w:
                break
            else:
                ans += 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
N = int(input())
c = input()
ans = 0
exchange = 0
for i in range(N):
    if c[i] == "W":
        exchange = i
        break
else:
    print(0)
    sys.exit()

for i in range(N):
    # print(i+1,"回目")
    # print("exchange=",exchange)
    # print("c=",c)
    if N-1-i >exchange:
        if c[-(i+1)] =="R":
            c = list(c)
            c[exchange] = "R"
            c[-(i+1)] = "W"
            c = "".join(c)
            # c = c[:exchange]+"R"+c[exchange+1:]
            # print("newc=",c)
            # c = c[:-(i+1)]+"W"+c[-(i+1)+1:]
            # print("newc=",c)
            ans += 1
            for k in range(exchange+1,N):
                if c[k] == "W":
                    exchange = k
                    break
            else:
                break
    else:
        break
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

n = int(input())
string = list(input())

if "W" not in string:
  print(0)
  sys.exit()
if "R" not in string:
  print(0)
  sys.exit()

result = 0
for i in range(-(-len(string) // 2)):
  for j in range(len(string)):
    if string[j] == "W":
      find_W = j
      break
  for k in range(len(string)-1, -1, -1):
    if string[k] == "R":
      find_R = k
      break
  if find_R < find_W:
    break
  else:
    string[find_W] = "R"
    string[find_R] = "W"
    result += 1

print(result)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = str(input())
cn = [0]*n
for i in range(n):
    if c[i]=="R":
        cn[i]=1


ans = 0
k=n-1
b=0

for i in range(n):
    if b==1:
        break
   
    if cn[i]== 0:
        for j in range(k,0,-1):

            if cn[j]==1:
                k =j
                if i < j:
                    cn[i]=1
                    cn[j]=0
                    ans +=1
                    break
                elif i>=j:
                    b=1
                    break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

class Levenshtein:

    def initArray(self,str1,str2):
        distance = []
        for i in range(len(str1)+1):
            distance.append([0]*(len(str2)+1))
            distance[i][0] = i
        for j in range(len(str2)+1):
            distance[0][j] = j
        return distance

    def editDist(self,str1,str2,distance):
        dist = [0]*3
        for i in range(1,len(str1)+1):
            for j in range(1,len(str2)+1):
                dist[0] = distance[i-1][j-1] if str1[i-1]==str2[j-1] else distance[i-1][j-1]+1
                dist[1] = distance[i][j-1]+1
                dist[2] = distance[i-1][j]+1
                distance[i][j]=min(dist)
        return distance[i][j]

    def __init__(self,str1,str2):
        self.str1 = str1
        self.str2 = str2
        Levenshtein.distance = self.initArray(str1,str2)
        Levenshtein.dist = self.editDist(str1,str2,Levenshtein.distance)

N = int(input())
S = input()

c = Counter(S)
S_target = 'R' * c['R'] + 'W' * c['W']

leven = Levenshtein(S, S_target)
print(leven.dist // 2)

Submission status: Time Limit Exceeded

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

if "R" not in l or "W" not in l:
    print(0)
    exit()

cnt = 0
for i in range(n):
    if l[i] == "W":
        if "R" not in l[i:]:
            break
        else:
            l1 = list(reversed(l))
            k = n-1 - l1.index("R")
            l[i], l[k] = l[k], l[i]
            cnt += 1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
c=input()
ans=0
def happy(c,n):
    allw=['W']*n
    allr=['R']*n
    if c==allw or c==allr:
        return True
    else:
        t=0
        for i in range(n-1):
           if c[i+1]!=c[i]:
               t+=1
        if t==1 and c[0]=='R':
            return True
        else:
            return False
arr=[]
for i in c:
    arr.append(i)
while happy(arr,n)!=True:
    br=False
    for i in range(n-1):
        if arr[i]=='W':
            for j in range(1,n):
                if arr[-j]=='R':
                    br=True
                    arr[i]='R'
                    arr[-j]='W'
                    ans+=1
                    break
        if br:
            break
print(ans)

Submission status: Time Limit Exceeded

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

def main():
    cnt = 0
    for i in range(0, len(c)):
        if c[i] == "W":
            cnt = cnt + 1
    
    if cnt == 0:
        print(0)
        return 0
    else:
        num = 0
        for j in range(0, int(n/2)):
            for k in range(n-1, int(n/2)-1, -1):
                if c[j] == "W" and c[k] == "R":
                    num = num + 1
                    tmp = c[j]
                    c[j] = c[k]
                    c[k] = tmp 
                    break
        print(num)
        return 0
main()

Submission status: Time Limit Exceeded

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

end = []
for i in range(n+1):
    end.append("R"*i + "W"*(n-i))
#print(end)

newc = "".join(c)
ans = 0
if newc in end:
    print(ans)
    exit()
while newc not in end:
    for i in range(n):
        if c[i] == "W":
            c[i] = "R"
            break
    for i in reversed(range(n)):
        if c[i] == "R":
            c[i] = "W"
            break
    newc = "".join(c)
    ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
line = list(input())

# print(line)
bottom_w = N
top = 0
count = 0
while(bottom_w > top):
    for i in reversed(range(bottom_w)):
        if(line[i]=='R'):
            bottom_w = i
            break
    if(line[-1]=='W' and bottom_w == N):
        print(0)
        exit()
    if(bottom_w <= top):
        break
    for i in range(top,N):
        if(line[i]=='W' and bottom_w > i):
            # print("line",i,line[i])
            # print("swap",i,bottom_w)
            count += 1
            line[bottom_w] = 'W'
            top = i+1
            break
print(count)

Submission status: Time Limit Exceeded

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

array = list(s)
r = len(s.replace('W', ''))
w = n - r
ans = min(r,w)

i = 0
j = len(array)-1
count = 0

while True:
  while len(array) > i and array[i] == 'R':
    i += 1
    
  while j > 0 and array[j] == 'W':
    j -= 1
    
  if(i>j):
    break
    
  array[i], array[j] = array[j], array[i]
  count += 1
  
print(min(count, ans))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = list(input())
count = 0
i = 0
frag = 0

while frag == 0:
  c_r = c[::-1]
  #print((len(c)-1) - c_r.index('R'))
  if c.count('W') == 0 or c.count('R') == 0:
    break

  if c.index('W') < ((len(c)-1) - c_r.index('R')):
    c[(len(c)-1) - c_r.index('R')] = 'W'
    c[c.index('W')] = 'R'
    #print(c)
    count += 1
  else:
    frag = 1
print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = list(input())
if len(set(s)) == 1:
  print(0)
  exit()
i = 0
while True:
    wi = s.index("W")
    ri = "".join(s).rindex("R")
    if wi < ri:
        s[wi], s[ri] = s[ri], s[wi]
        i += 1
    else: break
print(i)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Aug  2 21:11:34 2020

@author: NEC-PCuser
"""

N = int(input())

s = input()

l = 0
r = len(s) - 1
count = 0
while True:
	flg = False
	for i in range(l, r):
		if (s[i] == 'W'):
			l = i + 1
			flg = True
			break
	for j in range(r, l - 1, -1):
		if (s[j] == 'R'):
			r = j - 1
			if flg:
				count += 1
			break
	if flg == False:
		break
print(count)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
C = deque(list(input()))

cnt = 0

while len(set(C)) > 1:
    if C[0] == 'W' and C[-1] == 'R':
        cnt += 1
        C.popleft()
        C.pop()
    else:
        if C[0] == 'R':
            C.popleft()
        if C[-1] == 'W':
            C.pop()

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
def change(S,index,color):
	lstS = list(S)
	lstS[index] = color
	S = ''.join(lstS)

	return S


if __name__ == '__main__':
	N = int(input())
	S = input()
	L = 0
	R = N-1
	count = 0
	if S.count('W') == 0 or S.count('R') == 0:
		R = -1
	while(L < R):
		while(S[L] == 'R'):
			L += 1
		while(S[R] == 'W'):
			R -= 1
		if L > R:
			break
		S = change(S,L,'R')
		S = change(S,R,'W')
		L += 1
		R -= 1
		count += 1

	print(count)

Submission status: Time Limit Exceeded

Solution code:
import copy
N = int(input())
C = str(input())
D = copy.copy(C)
while D.count("WR") > 0:
  D = D.replace("WR","RW")

ans = 0

for i in range(N):
  if D[i] == "W":
    break
  if D[i] != C[i]:
    ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, re
def i_input(): return int(input())
def s_input(): return input()
sys.setrecursionlimit(10 ** 6)

def main():
    n = i_input()
    s = list(s_input())

    r_count = s.count('R')
    w_count = n - r_count

    if r_count == n or w_count == n:
        print(0)
        exit()

    r_s = s[::-1]

    count = 0

    index = 0
    for i in range(len(s)):
        if r_s[i] == 'W':
            continue
        for j in range(index, n - i - 1):
            if s[j] == 'R':
                continue
            index = j + 1
            r_s[n-index] = 'R'
            count += 1
            break

    print(min(count, min(r_count, w_count)))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:

def main():
    N = int(input())
    s = list(input())

    cnt = 0
    prej = N
    for i in range(N):
        if s[i] == "R":
            continue
        if i >= prej:
            break
        for j in list(range(i+1,prej))[::-1]:
            if s[j] == "W":
                continue
            if i >= j:
                break
            cnt += 1 
            prej = j
            break
    print(cnt)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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


ans = 0

if c.count("R")==0 or c.count("W") == 0:
    ans = 0
for n in range (N):
    left_W = c[:n].count("W")
    right_R = c[n:].count("R")
    if left_W == right_R:
        ans = right_R
        break
print(ans)

Submission status: Time Limit Exceeded

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

for i in range(len(c)):
    
    c = c.lstrip("R")
    if c.count("R")==0:
        break
    
    firstW = c.find("W")
    lastR = c.rfind("R")
    
    c=list(c)
    c[firstW] = "R"
    c[lastR] = "W"
    c="".join(c)
    
#    print(c)


print(i)

Submission status: Time Limit Exceeded

Solution code:
def main():
    N=int(input())
    c=input()
    
    #x...WR
    #o...RR, RW, WW
    #Wが来たらそれ以降はW
    #R(0個以上)+W(0個以上)
    
    i=0
    for _ in range(N):
        if 'WR' in c:
            x=c.index('WR')  
            y=N-c[::-1].index('R')-1
            #print(x,y)
            c=c[:x]+'R'+c[x+1:y]+'W'+c[y+1:]
            #print(c)
            i+=1
            
    print(min(c.count('R'),c.count('W'),i))
    

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
clst = list(input())
cnt = 0
while True:
    if 'R' not in clst or 'W' not in clst:
        break
    else:
        rnum = [i for i, c in enumerate(clst) if c == 'R'][-1]
        wnum = clst.index('W')

    if wnum >= rnum:
        break
    else:
        clst[rnum] = 'W'
        clst[wnum] = 'R'
        cnt += 1

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
line = list(input())

# print(line)
bottom_w = N
top = 0
count = 0
while(bottom_w > top):
    for i in reversed(range(bottom_w)):
        if(line[i]=='R'):
            bottom_w = i
            break
    if(line[-1]=='W' and bottom_w == N):
        print(0)
        exit()
    for i in range(top,N):
        if(line[i]=='W' and bottom_w > i):
            # print("line",i,line[i])
            # print("swap",i,bottom_w)
            count += 1
            line[bottom_w] = 'W'
            top = i+1
            break
print(count)

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline 
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def main():
    n = i_input()
    s = list(s_input())

    r_count = s.count('R')
    w_count = n - r_count

    if r_count == n or w_count == n:
        print(0)
        exit()

    r_s = s[::-1]

    count = 0

    index = 0
    for i in range(len(s)):
        if r_s[i] == 'W':
            continue
        for j in range(index, n - i - 1):
            if s[j] == 'R':
                continue
            index = j + 1
            r_s[n-index] = 'R'
            r_s[i] = 'W'
            count += 1
            break

    print(min(count, min(r_count, w_count)))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

cnt = 0
prej = N
for i in range(N):
    if s[i] == "R":
        continue
    for j in list(range(i+1,prej))[::-1]:
        if s[j] == "W":
            continue
        if i >= j:
            break
        cnt += 1 
        prej = j
        break
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import re
n = input()
def check(content):
  pattern = '.*(WR)+'
  result = re.match(pattern, content)
  if result == None:
    return False
  else:
    return True
  
data = input()
counter = 0

while check(data):
  # 一番左のWをRに
  data = data.replace('W','R',1)
  # print('first {}'.format(data))
  # 一番右のRをWに
  data = data[::-1].replace('R','W',1)[::-1]
  # print('second {}'.format(data))
  counter += 1

print(counter)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=raw_input()

def solve(s,n):
    if "W" not in s or "R" not in s or s.find("WR")==-1:
        return 0

    else:
        arr=list(s)
        i=0
        j=n-1
        count=0
        brr=list(sorted(s))

        while arr!=brr:
            if arr[i]=="W" and arr[j]=="R":
                
                count += 1
                arr[i]="R"
                arr[j]="W"
                i+=1
                j-=1

            elif arr[i]=="W" and arr[j]=="W":
                j-=1
            elif arr[i]=="R" and arr[j]=="R":
                i+=1
            else:
                i+=1
                j-=1
        return count
print(solve(s,n))

Submission status: Time Limit Exceeded

Solution code:
i=int(input())
s=list(input())
count=0
for j in range (i-1,-1,-1):
    if s[j]=="R":
        for k in range (j):
            if s[k]=="W":
                s[j],s[k]=s[k],s[j]
                count+=1
                break
print (count)

Submission status: Time Limit Exceeded

Solution code:
a=int(input())
b=input()
r_num=0
w_num=0
for i in b :

  if i=='W' :
    w_num+=1
  else :
    r_num+=1
c=''
for i in range(r_num):
  c+='R'
for i in range(w_num) :
  c+='W'
count=0

for i in range(r_num) :
  if c[i]!=b[i] :
    count+=1
print(count)

Submission status: Time Limit Exceeded

Solution code:
def check(c):
    return 'WR' in c

def main():
    N = int(input())
    c = list(input())
    ans = 0
    while check(''.join(c)):
        i1 = c.index('W')
        i2 = len(c) - c[::-1].index('R') - 1
        c[i1], c[i2] = c[i2], c[i1]
        ans += 1
    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
N = int(input())
c = input()
ans = 0
exchange = 0
for i in range(N):
    if c[i] == "W":
        exchange = i
        break
else:
    print(0)
    sys.exit()

for i in range(N):
    if N-1-i >exchange:
        if c[-(i+1)] =="R":
            c = c[:exchange]+"R"+c[exchange+1:]
            c = c[:-(i+1)]+"W"+c[(i+1)+1:]
            ans += 1
            for k in range(exchange+1,N):
                if c[i] == "W":
                    exchange = k
                    break
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[2]:


import collections


# In[18]:


N = int(input())
clist = input()


# In[19]:


c = collections.Counter(clist)
cr = c["R"]
mylist = [x for x in clist]
mylist_r = list(reversed(mylist))
ans = 0
while mylist[:cr].count("R") != cr:
    W_i = mylist.index("W")
    R_i = mylist_r.index("R")
    mylist[W_i] = "R"
    mylist[N-R_i-1] = "W"
    mylist_r[N-W_i-1] = "R"
    mylist_r[R_i] = "W"
    ans += 1
print(ans)


# In[ ]:

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

def solve():
    N = II()
    C = LS()

    j = N-1
    cnt = 0
    # print(C)
    for i in range(N):
        if i >= j: break
        ci = C[i]
        if ci == 'W':
            # change
            # print(i, j)
            for k in range(j, i, -1):
                ck = C[k]
                if ck == 'R':
                    # print(i, j)
                    C[i], C[k] = ck, ci
                    cnt += 1
                    j = k-1
                    break
        # print(C)
    print(cnt)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())
cFixed = [x for x in c]
cFixed.sort()
ans = 0
for i in range(n):
	if c[i] != cFixed[i]:
		for j in range(i+1 , n):
			if c[j] == "R" and c[j] != cFixed[j]:
				c[i] = "R"
				c[j] = "W"
				ans += 1


print(ans)

Submission status: Time Limit Exceeded

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

w = []
r = []
for i in range(n):
  if c[i] == 'W':
    w.append(i+1)
  else:
    r.append(i+1)

w_len = len(w)
r_len = len(r)
if w_len == 0 or r_len == 0:
  print(0)
  exit(0)

count = 0
for i in range(n):
  tmp = w[i]
  w[i] = r[r_len-i-1]
  r[r_len-i-1] = tmp
  count += 1
  
  if max(r) < min(w):
    print(count)
    exit(0)
print(count)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
N = int(input())
line = list(input())
count = 0
for i in range(len(line)):
    if line[i] == 'W':
        for j in range(len(line) - 1, i, -1):
            if line[j] == 'R':
                line[i] , line[j] = line[j], line[i]
                count += 1
                break
print(count)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
C = input()
C = C.lstrip('R').rstrip('W')

i = 0
while len(C) > 0:
    l = C.index('R')
    r = C[::-1].index('W')
    n = min(l, r)
    C = C[n:]
    C = C[:-n]
    C = C.lstrip('R').rstrip('W')
    i += n
else:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
i,j = 0, len(c)-1
count = 0
while i!=j:
    if c[i]=='W' and c[j]=='R':
        i+=1
        j-=1
        count += 1
        continue
    if c[i]=='W' and c[j]!='R':
        j -= 1
        continue
    if c[i]!='W' and c[j]=='R':
        i += 1
    if abs(i-j)==1:
        break
print(count)

Submission status: Time Limit Exceeded

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

ar = c.count('R')
aw = c.count('W')

anses = []
for i in range(n + 1):
  rtow, wtor = 0, 0
  for j, e in enumerate(c):
    if j < i:
      if e != 'R':
        rtow += 1
    else:
      if e != 'W':
        wtor += 1

  ans = max(rtow, wtor)
  anses.append(ans)

print(min(anses))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=raw_input()

def solve(s,n):
    if "W" not in s or "R" not in s:
        return 0
    if s.find("WR")==-1:
        return 0
    else:
        arr=list(s)
        i=0
        j=len(s)-1
        count=0
        r=s.count("R")
        w=s.count("W")
        s1="R"*r+"W"*w
        brr=list(s1)

        while arr!=brr:
            if arr[i]=="W":
                if arr[j]=="R":
                    count += 1
                    arr[i]="R"
                    arr[j]="W"
                    i+=1
                    j-=1

                else:
                    j-=1
            else:
                if arr[j]=="R":
                    i+=1
                else:
                    i+=1
                    j-=1
        return count
print(solve(s,n))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Aug  2 21:11:34 2020

@author: NEC-PCuser
"""

N = int(input())

s = input()

l = 0
r = len(s) - 1
count = 0
while True:
	flg = False
	for i in range(l, r):
		if (s[i] == 'W'):
			l = i + 1
			flg = True
			break
	for j in range(r, l - 1, -1):
		if (s[j] == 'R'):
			r = j - 1
			if flg:
				count += 1
				str_list = list(s)
				str_list[l - 1] = 'R'
				str_list[r + 1] = 'W'
				s = "".join(str_list)
			break
	if flg == False:
		break
print(count)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

N=int(input().rstrip('\n'))
S=list(input().rstrip('\n'))
score = [S.count('R'),S.count('W')]
sta = 'R'
for i in range(N-1):
  if S[i] != sta:
    a = S[:i].count('W')
    b = S[i:].count('R')
    score.append(max(a,b))
    sta = S[i]
print(min(score))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = input()
import numpy as np
a = np.zeros(len(c))
for i in range(N):
    if c[i] == "R":
        a[i] = 1
count = 0
while np.sum(a) >= 1:
    for i in range(len(a)):
        if a[i] == 0:
            a = a[i:]
            break
    if a[0] == 1:
        break
    for i in range(len(a)):
        i = i+1
        if a[-i] == 1:
            a[-i] = 0
            a[0] = 1
            count += 1
            break
print(count)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import re

N = int(input().strip())
# C = [c for c in input().strip()]
C = input().strip()

G = re.compile(r"^R*W*$")
cnt = 0


def rep(i, c, r, w):
    if i == r:
        return "W"
    elif i == w:
        return "R"
    else:
        return c

while not G.match(C):
    cnt += 1
    r = C.rfind("R")
    w = C.find("W")
    C = "".join([
        rep(i, c, r, w)
        for i, c in enumerate(C)
    ])
    # break

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import re

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

def set_c(a):
    a = re.sub('^[R]*W', 'W', a)
    a = re.sub('R[W]*$', 'R', a)
    return a

for i in range(n):
    c = set_c(c)
    if c == '':
        break
    elif 'W' not in c or 'R' not in c:
        break
    c = 'R' + c[1:-1] + 'W'
        
print(i)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
m = str(input())

red = []
white = []
for i in range(n):
    if m[i] == 'R':
        red.insert(0, i)
    else:
        white.append(i);

re = len(red)
wh = len(white)
if re == 0 or wh == 0:
    print(0);
else:
    k = 0;
    for j in range(min(re,wh)):
        if red[j] > white[j]:
            k += 1;

    print(k);

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import math
import scipy as sp
import queue
import collections

MOD = 10 ** 9 + 7
INF = 10 ** 9

def main(kwargs):
    n = kwargs["n"]
    C = kwargs["C"]
    res = n

    for i in range(n + 1):
        left = C[:i+1].count("W")
        right = C[i+1:].count("R")
        tmp = max([left, right])
        res = min(res, tmp)
    return res

if __name__ == "__main__":
    kwargs = {}

    cin = input().split()
    kwargs["n"] = [int(i) for i in cin][0]
    cin = input().split()[0]
    kwargs["C"] = [i for i in cin]

    cout = main(kwargs)
    print(cout)