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())
pebbles = list(input())
counts  = 0
flag = False

def pebbles_check(pebbles):
      for i in range(len(pebbles)-1):
            if pebbles[i] == "W" and pebbles[i+1] == "R":
                  return False
      return True
    
def process_1(pebbles,n):
      a,b = -1,-1
      
      for i in range(0,n):
            if pebbles[i] == "W":
                  a = i
                  break
            
      for i in range(n-1,a,-1):
            if pebbles[i] == "R":
                  b = i
                  break
            
      if a != -1 and b != -1:
            pebbles[a],pebbles[b] = pebbles[b],pebbles[a]
      
      return pebbles

def process_2(pebbles,n):
      for i in range(n-1,-1,-1):
            if pebbles[i] == "R":
                  pebbles[i] = "W"
                  break
      
      return pebbles

flag = pebbles_check(pebbles)
#print(pebbles)
#print(flag)


while(flag == False):
      counts += 1
      process_1(pebbles,n)          # process_1: 石を 2個選び (隣り合っていなくてもよい)、それらを入れ替える。
      #print(pebbles)
      
      if pebbles_check(pebbles) == False:
            counts += 1
            process_2(pebbles,n)    # process_2: 石を 1個選び、その石の色を変える (赤なら白に、白なら赤に)。
            #print(pebbles)
      flag = pebbles_check(pebbles)


print(counts)

Submission status: Time Limit Exceeded

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

def del_(string):
  while(string[0] == "R" or string[-1] == "W"):
    if string[0] == "R":
      del string[0]
    if len(string) == 0:
      break
    if string[-1] == "W":
      del string[-1]
    if len(string) == 0:
      break

def change(string):
  string[0] = "R"
  string[-1] = "W"

result = 0
while len(string) > 0:
  del_(string)
  if len(string) == 0:
    break
  else:
    change(string)
    result += 1
    
print(result)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
cnt = 0
if c.count('WR')==0:
  print(0)
else:
  while c.count('WR')>1:
    pre = -1
    post = -1
    for i,j in enumerate(c):
      if i==len(c)-1:
        continue
      if j=='W' and c[i+1]=='R':
        if pre==-1:
          pre = i
        elif post==-1:
          post = i+1
        else:
          c = c[:pre]+'R'+c[pre+2:post]+'W'+c[post+1:]
          cnt += 1
          break
  for i in c[::-1]:
    if i=='R':
      cnt += 1
    else:
      break
  print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())
sc = list(reversed(c))
ans = 0
r = 0
flg  = False

if 'W' not in set(c) or 'R' not in set(c):
    print(ans)


else:
    for i in range(n):
        if flg:
            break
        if c[i] == 'W':
            for j in range(r, n):
                if sc[j] == 'R':
                    if n >= i+j+2:
                        c[i] = 'R'
                        c[-1*j-1] = 'W'
                        ans += 1
                        sc = list(reversed(c))
                        break
                    else:
                        flg = True
                        break

                else:
                    r += 1
            

    print(ans)

Submission status: Time Limit Exceeded

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

def cut(c):
    num = 0
    for i in range(N):
        if c[i]!='R':
            break
        else:
            num+=1
    return c[num:]

c = cut(c)
cnt = 0

def change(c):
    nu = 0
    num = c[::-1].find('R')
    return c[1:len(c)-1-num]+'W'+c[len(c)-num:]
    
while 'R' in c:
    c = change(c)
    c = cut(c)
    cnt +=1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy
import itertools
def invalid(c):
  num = 0
  for i in range(len(c) - 1):
    if c[i: i+2] == [-1, 1]:
      num += 1
  return num
n = int(input())
c = list(input())
for i in range(n):
  if c[i] == 'W':
    c[i] = -1
  else:
    c[i] = 1
now_invalid = invalid(c)
if not now_invalid:
  print(0)
  sys.exit()
cs = [[c]]
i = 1
while True:
  cs.append([])
  for cc in cs[-2]:
    for i in range(n):
      c_ = copy.deepcopy(cc)
      c_[i] *= -1
      if invalid(c_) == 0:
        print(len(cs) - 1)
        sys.exit()
      if invalid(c_) <= invalid(cc):
        cs[-1].append(c_)
    lis = list(itertools.combinations(list(range(n)), 2))
    for nums in lis:
      c_ = copy.deepcopy(cc)
      c_[nums[0]], c_[nums[1]] = c_[nums[1]], c_[nums[0]]
      if invalid(c_) == 0:
        print(len(cs) - 1)
        sys.exit()
      if invalid(c_) <= invalid(cc):
        cs[-1].append(c_)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = input()
ans = 0
for _ in range(N):
    fs = 0
    ls = len(c)
    for i, ci in enumerate(c):
        fs = i
        if ci == 'W':
            break
    for i , ci in enumerate(c[::-1]):
        if i + fs >= N:
            break
        ls -= 1
        if ci == 'R':
            break
    if fs == ls:
        break
    ans += 1
    c = c[fs + 1:ls]
    #print(c)
    if len(c) <= 1:
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# 整数の入力
import numpy as np
import sys
x=200000
sys.setrecursionlimit(x)

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


def check_condition(S):
    N = len(S)
    ind = np.where(S=="R")[0]
    if len(ind) == 0 or len(ind) == N:
        return True
    
    if np.max(ind) == len(ind) - 1:
        return True
    
    return False

def action(S):
    W_index = np.where(S=="W")[0][0]
    R_index = np.where(S=="R")[0][-1]
    S[W_index] = "R"
    S[R_index] = "W"
    return S

def alter(S, M):
    if check_condition(S):
        return M
    
    S = action(S)
    
    return alter(S, M+1)

S = np.array(list(S))
print(alter(S,0))

Submission status: Time Limit Exceeded

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

for i in range(n-1):
    if c[i] == "W":
        for j in range(n-i-1):
            if c[n-1-j]=="R":
                c[i]="R"
                c[n-1-j]="W"
                ans+=1
                break

print(ans)

Submission status: Time Limit Exceeded

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

c = [c[i] for i in range(N)]

cR = c.count('R')
cW = c.count('W')

listR = [i for i, x in enumerate(c) if x == 'R']
listW = [i for i, x in enumerate(c) if x == 'W']

if all([i == 'R' for i in c[:cR]]):
    print(0)
    exit()

if all([i == 'W' for i in c[cR:cR+cW]]):
    print(0)
    exit()

cnt = 0

for i in range(N):
        c[listR[-(i+1)]] = 'W'
        c[listW[i]] = 'R'
        cnt += 1
        if all([i == 'R' for i in c[:cR]]):
            print(cnt)
            break

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

c_list = [s for s in input()]
cr = list(reversed(c_list))
back = N - 1


def check(forward):
    global back
    for i in range(back, -1, -1):
        if i < forward:
            return -1
        if c_list[i] == "R":
            back -= 1
            return i
    return -1


count = 0
for i, c in enumerate(c_list):
    if c_list[i] == "W":
        temp = check(i + 1)
        if temp != -1:
            c_list[i] = "R"
            c_list[temp] = "W"
            count += 1
        else:
            break
print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c_str = input()
c_list = list(c_str)

cnt = 0
flag = 1
w_pos = 0
r_pos = 0

while flag:
    for i in range(0,n):
        if c_list[i] == "W":
            w_pos = i
            break
        if i == n-1:
            w_pos = n-1
    for j in reversed(range(0,n)):
      if c_list[j] == "R":
        r_pos = j
        break
    if w_pos < r_pos:
        c_list[w_pos] = "R"
        c_list[r_pos] = "W"
        cnt += 1
    else:
      flag = 0

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
C = input()
c = [0]*N
for i in range(N):
  if C[i] == 'R':
    c[i] = 1
  elif C[i] == 'W':
    c[i] =0
    
def ok(c):
  for i in range(len(c)-1):
    if(c[i] < c[i+1]):
      return False
  return True

def change(c):
  r = -1
  w = -1
  l = len(c)-1
  for i in range(l):
    if c[i] == 0 and w<0:
      w = i
    if c[l-i] == 1 and r<0:
      r = l-i
    if w >0 and r > 0:
      break
  c[w] = 1
  c[r] = 0
  
  return c
  
cnt = 0
while not ok(c):
  c = change(c)
  cnt +=1
  
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
# 整数の入力
import numpy as np
N = int(input())
S = input()


def check_condition(S):
    N = len(S)
    ind = np.where(S=="R")[0]
    if len(ind) == 0 or len(ind) == N:
        return True
    
    if np.max(ind) == len(ind) - 1:
        return True
    
    return False

def action(S):
    W_index = np.where(S=="W")[0][0]
    R_index = np.where(S=="R")[0][-1]
    S[W_index] = "R"
    S[R_index] = "W"
    return S

def alter(S, M):
    if check_condition(S):
        return M
    
    S = action(S)
    
    return alter(S, M+1)

S = np.array(list(S))
print(alter(S,0))

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
N = int(input())
c = str(input())
l = N-1
s = 0
for i in range(int(N)):        
    if c[i] == 'W':
        for j in range(l,i,-1):
            if c[j] == 'R':
                l=j-1
                s = s+1
                break
    if l < i:
        break
print(s)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
n=0
if S.find("W")==-1 or S.find("R")==-1:
  print(0)
else:
  while S.find("W")<=S.rfind("R"):
    S = S[S.find("W")+1:S.rfind("R")]
    n+=1
  print(n)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = []
c = input()
S.extend(c)

if "W" in S and "R" in S:
    for i in range(N):
        S_r = S[::-1]
        min_W = S.index("W")
        max_R = N - 1 - S_r.index("R")
        if min_W>max_R:
            print(i)
            break
        S[min_W],S[max_R] = S[max_R],S[min_W]
else:
    print(0)

Submission status: Time Limit Exceeded

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

ans = 0

while len(arr) > 1:
    left = -1
    right = -1

    if "W" in arr:
        left = arr.index("W")
    else:
        break
    if "R" in arr:
        right = len(arr) - arr[::-1].index("R") - 1
    else:
        break

    if left == -1 or right == -1 or left > right:
        break
    else:
        arr = arr[left + 1:right]
        ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())
sc = list(reversed(c))
ans = 0
r = 0


if 'W' not in set(c) or 'R' not in set(c):
    print(ans)

else:
    for i in range(n):
        if c[i] == 'W':
            for j in range(r, n):
                if sc[j] == 'R':
                    if n >= i+j+2:
                        c[i] = 'R'
                        c[-1*j-1] = 'W'
                        ans += 1
                        sc = list(reversed(c))
                        break
                    else:
                        flg = False
                        break

                else:
                    r += 1

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input().split()
w_index = []
r_index = []
length_ = len(S[0])

for i in range(len(S[0])):
    s = S[0][i]
    if s =='W':
        w_index.append(i)
    else:
        r_index.append(i)
        
if len(w_index) == 0 or len(r_index) == 0:
    print(0)

else:
    
    ng_num = 0
    for r_i in range(len(r_index)):

        if r_i not in r_index:
            ng_num += 1
        
    print(ng_num)

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(len(c)):
    if c[j] == "R":
        r_idx.append(j)
    elif c[j] == "W":
        w_idx.append(j)

ans = [0 for _ in range(min(len(r_idx), len(w_idx)))]
if len(ans) == 0:
    print(0)
else:
    for i in range(min(len(r_idx), len(w_idx))): # i is number of op1
        c_i = c[:]
        for j in range(i):
            c_i = op1(c_i, w_idx[j], r_idx[-j - 1])
            ans[i] += 1
        if "W" in "".join(c_i).rstrip("W"):
            ans[i] += "".join(c_i).rstrip("W").count("W")
    print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = list(input())
ans = 0
while True:
    x, y = -1,-1
    for i in range(len(c)-1,-1,-1):
        if c[i] == "R":
            x = i
            break
    for j in range(len(c)):
        if c[j] == "W":
            y = j
            break
    if x == -1 or y == -1:
        break
    elif x-y == -1:
        break
    else:
        c[i],c[j] = c[j],c[i]
        ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
N = int(input())
c = str(input())
l = N-1
s = 0
for i in range(int(N)):        
    if c[i] == 'W':
        for j in range(l,i,-1):
            if c[j] == 'R':
                l=j-1
                s = s+1
                break

print(s)

Submission status: Time Limit Exceeded

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

if "R" not in C:
    print(0)
    exit()
count = 0

for i in range(N):
    if C[i] == 'W':

        index = C.rfind('R', i)
        if index >= 0:
            count += 1
        c = list(C)
        c[i] = 'R'
        c[index] = 'W'
        C = "".join(c)
    if 'R' not in C[i+1:]:
        break

print(count)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
c = input()
l =list(c)
L = len(l)//2
ans = 0

for i in range(n-1):
    for j in range(n-1,i,-1):
        if l[i]== 'W' and l[j] == 'R':
            l[j] = 'W'
            ans += 1
            break
print(ans)

Submission status: Time Limit Exceeded

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

for i in range(1000000000):
    if not "W" in c or not "R" in c :
        print(i)
        exit()
    cr = c[:]
    cr.reverse()
    w =  c.index("W")
    r = cr.index("R")
    
    c[-(r+1)] = "W"
    c.pop(w)
    if w > len(c)-r:
        print(i)
        exit()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
stones = [l for l in input()]

cnt = 0
for i in range(N//2):
    for j in range(N-1, i , -1):
        if stones[i] == 'W' and stones[j] == 'R':
            stones[i] = 'R'
            stones[j] = 'W'
            cnt += 1
            break
            
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# template: v1.3.1

import io
import sys
import math

### DEBUG ###
_DEB = 0  # 1:ON / 0:OFF

_INPUT = """\
RWRWRW
"""
_EXPECTED = """\
2

"""
if _DEB:
    sys.stdin = io.StringIO(_INPUT)
    print("!! Debug Mode !!")

def logd(str):
    if _DEB: print(f"[deb] {str}")


### INPUT ####
n = int(input())
c = input()
c=c.replace("R","0")
c=c.replace("W","1")
c=[int(x) for x in c]

### Solve ####
def solve():
    # Process
    ans=0
    id1=0
    for i in reversed(range(n)):
        id0=-1
        if c[i] == 0:
            id0=i
            for j in range(id1,id0):
                if c[j]==1:
                    id1=j
                    c[i]=1
                    c[j]=0
                    ans+=1
                    break
                
            if[i]==0:
                c[i]=1
                ans+=1

    # OUPUT
    ans = str(ans)
    print(ans)
    return ans

### MAIN ###
if __name__ == "__main__":
    ans = solve()

    # Checker
    if _DEB:
        if _EXPECTED.strip() == ans.strip(): print("\n!! Success !!")
        else: print(f"\n!! Failed... !!\nANSWER:   {ans}\nExpected: {_EXPECTED}")

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3


def count_WR(stones):
    return stones.count('WR')


def solve(stones, count):
    # 「もっとも右にR」を「もっとも左にあるW」と交換する
    if count_WR(stones) == 0:
        return count

    index_R = stones.rindex('R')
    index_W = stones.index('W')
    stones_list = list(stones)

    stones_list[index_R], stones_list[index_W] = stones_list[
        index_W], stones_list[index_R]

    new_stones = ''.join(stones_list)

    count += 1
    return solve(new_stones, count)


if __name__ == "__main__":
    N = int(input())
    stones = input()

    count = 0

    result = solve(stones, count)
    print(result)

Submission status: Time Limit Exceeded

Solution code:
import sys
def first_white(c):
    for i,ele in enumerate(c):
        if ele == 0:
            return i
    return -1
        
def last_red(c):
    for i in range(len(c)-1, -1, -1):
        if c[i] == 1:
            return i
    return -1
  
n = int(input())
c = [0 if x=='W' else 1 for x in input()]
counter = 0
while True:
    first_w = first_white(c)
    last_r = last_red(c)
    if (len(c) == 0) or (first_w < 0) or (last_r < 0) or (last_r < first_w):
        print(counter)
        sys.exit()
    c = c[first_w+1:last_r]    
    counter += 1

Submission status: Time Limit Exceeded

Solution code:
n= int(input())
s = input()
a = [str(c) for c in s]




def search(a,n):
  x = 0
  y = n-1
  for i in range(n):
    x = i
    if a[i] == 'W':
      break
  for i in range(n):
    y = n-i-1
    if a[n-i-1] == 'R':
      break
  return[x, y]

c = 0

for i in range(n):
  z = search(a, n)
  if z[0] < z[1]:
    a[z[0]], a[z[1]] =a[z[1]], a[z[0]]
    c += 1
  else:
    break
    
print(c)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
l = list(c)
ans = 0
while c.count("WR") > 0 :
    for i in range(n) :
        if l[i] == "W" :
            l[i] = "R"
            break
    for i in reversed(range(0,n)) :
        if l[i] == "R" :
            l[i] = "W"
            break
    c = ''.join(l)
    ans += 1
print(ans)

Submission status: Time Limit Exceeded

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

cnt = 0
for i in range(N):
  if c[i] == 'W':
    flag = True
    for j in range(N-1,i,-1):
      if c[j] == 'R':
        c[j] = 'W'
        cnt+=1
        flag = False
        break
    if flag:
      break
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys

rl = sys.stdin.buffer.readline
INF = sys.maxsize

X = int(rl())
SS = [c for c in rl().strip()]

W = ord(b'W')
R = ord(b'R')

last_pos = len(SS)-1
swap_count = 0
for i in range(len(SS)):
  if SS[i] == W:
    for j in range(last_pos, i, -1):
      if SS[j] == R:
        tmp = SS[i]
        SS[i] = SS[j]
        SS[j] = tmp
        last_pos = j-1
        swap_count += 1
        break

print(swap_count)

Submission status: Time Limit Exceeded

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

x =[0] * N

for i, cc in enumerate(c):
    if cc == "R":
        x[i] = 1

#一番左が赤だと削れる
#一番右が白だと削れる
cmd = 0
while len(x) > 0:
    while len(x) > 0 and x[0] == 1:
        x.pop(0)
    while len(x) > 0 and x[-1] == 0:
        x.pop(-1)
    while len(x) > 0 and x[0] == 0 and x[-1] == 1:
        x[0] = 1
        x[-1] = 0
        cmd += 1

print(cmd)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = input()
li = list(c)
count = li.count('R')
num = 0

for i in range(count):
    if li[i] == 'W':
        for j in range(len(li)-count):
            if li[j*(-1)-1] == 'R':
                li[i] = "R"
                li[j*(-1)-1] = 'W'
                num += 1



print(num)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
n = int(input())
c = input()
l=list(c)

r=0
while True:
  c="".join(l)
  lw=c.find("W")
  lr=c.find("R")
  rw=c.rfind("W")
  rr=c.rfind("R")
  if lw==-1:
    break
  if lw<rr:
    l=list(c)
    l[lw]='R'
    l[rr]='W'
    r=r+1
  else:
    break
print(r)

Submission status: Time Limit Exceeded

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

ans = 0
cnt = 0
w = 0
r = n-1
while True:
    cnt = w
    while cnt < n and C[cnt] != 'W': cnt += 1
    if cnt >= n:
        print(ans)
        exit()
    else:
        w = cnt
        while cnt+1 < n and C[cnt+1] != 'R': cnt += 1
        if cnt+1 >= n:
            print(ans)
            exit()
        else:
            while cnt != r and C[r] != 'R': r -= 1
            if cnt == r:
                print(ans)
                exit()
            else:
                ans += 1
                C[w], C[r] = C[r], C[w]

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
from itertools import groupby

N=int(input())
cs=input()
c=[cs[i] for i in range(N)]
ans=0
if c.count('R')==0 or c.count('W')==0:
    print(ans)
else:
    while True:
        gc=groupby(c)
        if len(list(gc))==2 and c[0]=='R':
            print(ans)
            break
        firstW=c.index('W')
        reversec=c[::-1]
        lastR=reversec.index('R')
        c[firstW]='R'
        c[-lastR-1]='W'
        ans+=1

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
count = 0
while True:
	if S.count('R') == 0:
			break
	if S[0] == 'R':
		S=S.lstrip('R')
	else:
		count += 1
		Rpos = S.rfind('R')
		S = S[1:Rpos]
print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
st = input()
from collections import deque,Counter
st = deque(st)
cnt = Counter(st)
ans = 0
while len(st) > 1:
    if st[0] == 'W' and st[-1] == 'R':
        ans += 1
        st.popleft()
        st.pop()
        cnt['R']-=1
        cnt['W']-=1
    elif st[0] =='R' and st[-1] == 'R':
        st.popleft()
        cnt['R']-=1
    elif st[0] == 'R' and st[-1] == 'W':
        st.popleft()
        st.pop()
        cnt['R']-=1
        cnt['W']-=1
    elif cnt['R']==0:
            break
    else:
        ans += 1
        cnt['R']-=1
        cnt['W']-=2
        st.popleft()
        st.pop()
        st.reverse()
        st.remove('R')
        st.reverse()
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())
sc = list(reversed(c))
ans = 0
flg = True

r = 0
l = 0

if 'W' not in set(c) or 'R' not in set(c):
    flg = False


while(flg):

    l = 0
    for i in range(l, n):
        r = 0
        if not flg:
            break

        if c[i] == 'W':
            for j in range(r, n):
                if sc[j] == 'R':
                    if len(c) >= i+j+2:
                        c[i] = 'R'
                        c[-1*j-1] = 'W'
                        ans += 1
                        sc = list(reversed(c))
                        break
                    else:
                        flg = False
                        break

                else:
                    r += 1
        else:
            l += 1
        
        if l >= n-1:
            flg = False
            break


print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
count = 0
while True:
	if S.count('R') == 0:
			break
	if S[0] == 'R':
		S=S.lstrip('R')
	else:
		count += 1
		S = S[1:]
		Rpos = S.rfind('R')
		S = S[:Rpos]
print(count)

Submission status: Time Limit Exceeded

Solution code:
a = [input() for i in range(2)]

arr_tmp = list(a[1])

N = int(a[0])

arr = []
for i in range(N):
	if arr_tmp[i] == 'W':
		arr.append(1)
	else:
		arr.append(0)

# swap sort
process_count = 0
for leftidx in range(N):
	
	if arr[leftidx] == 1:
		for rightidx in range(N-1,leftidx,-1):
			if arr[rightidx] == 0:
				arr[leftidx] = 0
				arr[rightidx] = 1
				process_count = process_count + 1
				break
			
print(process_count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())
mn = 100000
for i in range(len(c)) :
    left = c[:i+1]
    right = c[i+1:]
    cnt_lw = left.count("W")
    cnt_rr = right.count("R")
    ans = max(cnt_lw, cnt_rr)
    mn = min(ans,mn)
print(mn)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
r=0
w=0
p=0
count = 0
for i in range(len(c)):
    if c[i]=="R":
        r+=1
    else:
        w+=1
white = []

for i in range(len(c)):
    if c[i]=="R":
        r-=1
        
    else:
        white.append(r)
    if r==0:
        break
while True:
    if len(white)==0:
        print(count)
        break
    else:
        if count>=white[0]:
            print(count)
            break
        else:
            count+=1
            white.pop(0)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
C = input()
c = [0]*N
for i in range(N):
  if C[i] == 'R':
    c[i] = 1
  elif C[i] == 'W':
    c[i] =0
    
def ok(c):
  for i in range(len(c)-1):
    if(c[i] < c[i+1]):
      return False
  return True

def change(c):
  r = 0
  w = 0
  for i in range(len(c)):
    if c[i] == 0:
      w = i
      break
  for j in reversed(range(len(c))):
    if c[j] == 1:
      r = j
      break
  c[w] = 1
  c[r] = 0
  
  return c
  
cnt = 0
while not ok(c):
  c = change(c)
  cnt +=1
  
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = input()
list_c = [None] * N

for i in range(len(c)):
  list_c[i] = c[i]

def main():
  count = 0

  while True:
    if (''.join(list_c).find("WR") == -1):
      return(count)

    r_idx = ''.join(list_c).rfind("R")
    w_idx = ''.join(list_c).find("W")

    list_c[r_idx] = "W"
    list_c[w_idx] = "R"
    count += 1

print(main())

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
data=list(input())
if "W" not in data or "R" not in data:
    print(0)
else:
    s=0
    while True:
        first_w_index=0
        final_r_index=N
        for i in range(first_w_index,N):
            if data[i] =="W":
                first_w_index=i
                break
        for i in reversed(range(final_r_index)):
            if data[i] == "R":
                final_r_index=i
                break
        if first_w_index < final_r_index:
            data[first_w_index]="R"
            data[final_r_index]="W"
            s += 1
        else:
            print(s)
            break

Submission status: Time Limit Exceeded

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

x =[0] * N

for i, cc in enumerate(c):
    if cc == "R":
        x[i] = 1

#一番左が赤だと削れる
#一番右が白だと削れる
cmd = 0
while len(x) > 0:
    if x[0] == 1:
        x.pop(0)
    if len(x) > 0:
        if x[-1] == 0:
            x.pop(-1)
    if len(x) > 0:
        if x[0] == 0 and x[-1] == 1:
            x[0] = 1
            x[-1] = 0
            cmd += 1

print(cmd)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import functools
import math
from collections import Counter
from itertools import combinations
import re

def main_chk():
    N=int(input())
    C=input()

    chk = N - 1
    cnt = 0

    for i in range(N):
        if C[i] == 'W':
            for x in range(N-i):
                if C[chk-x] == 'R':
                    chk = chk - x
                    break
            if chk <= i:
                break
            else:
                cnt = cnt + 1
                chk = chk - 1
                if chk <= i + 1:
                    break

    print(cnt)

main_chk()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = []
c = input()
S.extend(c)
if "W" in S and "R" in S:
    for i in range(N):
        min_W = S.index("W")
        max_R = N - 1 - S[::-1].index("R")
        S[::-1]
        if min_W>max_R:
            print(i)
            break
        S[min_W],S[max_R] = S[max_R],S[min_W]
else:
    print(0)

Submission status: Time Limit Exceeded

Solution code:
n = input()
data = input()

w = []
r = []
for i in range(len(data)):
  if data[i] == "W":
    w.append(i)
  else:
    r.append(i)

ans = 0
if len(w) == 0:
  print(ans)
elif len(r) == 0:
  print(ans)
else:
  r = r[::-1]
  for i in range(len(data)):
    tmp_w = w.pop(0)
    tmp_r = r.pop(0)
    if tmp_w <= tmp_r:
      r.append(tmp_w)
      w.append(tmp_r)
      ans += 1
    else:
      print(ans)
      break

Submission status: Time Limit Exceeded

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

def cut(c):
    num = 0
    for i in range(N):
        if c[i]!='R':
            break
        else:
            num+=1
    return c[num:]


    
c = cut(c)
R = []
for i in range(len(c)-1, 0, -1):
    if c[i]=='R':
        R.append(len(c)-1-i)
cnt = 0

def change(c, num):
    return 'R'+c[1:len(c)-1-num]+'W'+c[len(c)-num:]
        
while 'R' in c:
    c = change(c, R[0])
    del R[0]
    c = cut(c)
    cnt +=1
    if len(R)==0 or R[0]>=len(c):
        break
print(cnt)

Submission status: Time Limit Exceeded

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

count = 0
disastar_list = []
last_one = False
for i in range(0,N-1):
    if c_list[i] == 'W' and c_list[i+1] == 'R':
        disastar_list.append(i)

while len(disastar_list) > 0:
    count = count + 1
    if(len(disastar_list) == 1):
        c_list[disastar_list[0]] = 'R'
        last_one = True
    else:
        c_list[disastar_list[len(disastar_list) - 1] + 1] = 'W'
        c_list[disastar_list[0]] = 'R'
        
        

    disastar_list = []
    for i in range(0, N -1):
        if c_list[i] == 'W' and c_list[i + 1] == 'R':
            disastar_list.append(i)
            if last_one == True:
                break


print(count)

Submission status: Time Limit Exceeded

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

if "R" in c and "W" in c:
    while True:
        c1=c[::-1]
        w_index=int(c.index("W"))
        r_index=int(N-1-c1.index("R"))
        if w_index-r_index==1:
             break
        ans+=1
        c[w_index]="R"
        c[r_index]="W"

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
count = 0
while True:
	if S == "":
		break
	if S[0] == 'R':
		S = S[1:]
	else:
		if S.count('R') == 0:
			break
		else:
			count += 1
			S = S[1:]
			Rpos = S.rfind('R')
			S = S[:Rpos]+S[Rpos+1:]
print(count)