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

Solution (Python):

import os
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from io import BytesIO, IOBase
from itertools import (
    accumulate, combinations, combinations_with_replacement, groupby,
    permutations, product)
from math import (
    acos, asin, atan, ceil, cos, degrees, factorial, hypot, log2, pi, radians,
    sin, sqrt, tan)
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits


def inp():
    return(int(input()))


def inlist():
    return(list(map(int, input().split())))


def instr():
    s = input()
    return(list(s[:len(s)]))


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








def main():
    n = inp()
    a = input()
    b = sorted(a)
    c = 0
    for i in range(n):
        if b[i] == "R" and a[i] != "R":
            c += 1
    print(c)



BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")




if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
C = input()
len_r, len_w = 0, 0
for c in C:
    if c == 'R':
        len_r += 1
    else:
        len_w += 1
c2 = 'R'*len_r + 'W'*len_w
cnt = 0
for a, b in zip(C, c2):
    if a != b:
        cnt += 1
print(cnt//2)

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

r=0
w=0

for i in range(n):
    if c[i]=="R":
        r+=1
    else:
        w+=1

umeru=0

for j in range(r):
    if c[j]=="W":
        umeru+=1

if r>=umeru:
    print(umeru)
else:
    print(umeru + (r-umeru))

Solution (Python):
n = int(input())
s = str(input())


r = 0
w = 0
w_num = 0


for i in s:
    if i == "R":
        r += 1


for j in s[0:r]:
    if j == "W":
        w_num += 1
print(w_num)

Solution (Python):
n=int(input())
s=input()
red=s.count('R')
print(red-s[:red].count('R'))

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


a=c.count("R")
l=[c[i] for i in range(a)]
print(l.count("W"))

Solution (Python):
def main(sample_file = ''):

    """ convenient functions
    
    
    
    
    
    """

    """convenient decorator
    
    
        
        
        
        
        
        
        
        
        
        
    """
    
    
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product 
    
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  
        b, e = 2, 0  
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):   
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict 
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest 
    from copy import deepcopy, copy 
    import operator
    from operator import itemgetter 
    
    
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd 
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    
    
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    AtoZ = list('abcdefghijklmnopqrsruvwxyz') 
    modpow = lambda a, n, p = MOD: pow(a, n, p) 
    def modinv(a, p = MOD):
        
        
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        
        
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    class SegTree:
        """
        ref: https://qiita.com/takayg1/items/c811bd07c21923d7ec69
        init(init_val, ide_ele): 配列init_valで初期化 O(N)
        update(k, x): k番目の値をxに更新 O(logN)
        query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
        """
        def __init__(self, init_val, segfunc, ide_ele):
            """
            init_val: 配列の初期値
            segfunc: 区間にしたい操作
            ide_ele: 単位元
            n: 要素数
            num: n以上の最小の2のべき乗
            tree: セグメント木(1-index)
            """
            n = len(init_val)
            self.segfunc = segfunc
            self.ide_ele = ide_ele
            self.num = 1 << (n - 1).bit_length()
            self.tree = [ide_ele] * 2 * self.num
            
            for i in range(n):
                self.tree[self.num + i] = init_val[i]
            
            for i in range(self.num - 1, 0, -1):
                self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

        def update(self, k, x):
            """
            k番目の値をxに更新
            k: index(0-index)
            x: update value
            """
            k += self.num
            self.tree[k] = x
            while k > 1:
                self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
                k >>= 1

        def query(self, l, r):
            """
            [l, r)のsegfuncしたものを得る
            l: index(0-index)
            r: index(0-index)
            """
            res = self.ide_ele
            l += self.num
            r += self.num
            while l < r:
                if l & 1:
                    res = self.segfunc(res, self.tree[l])
                    l += 1
                if r & 1:
                    res = self.segfunc(res, self.tree[r - 1])
                l >>= 1
                r >>= 1
            return res

    
    
    
    
    
    
    
    

    def BellmanFord(N, M, ABC, vertex_start, vertex_end, value_if_inf = -1, find_shortest = False):
        """to calculate furthest or shortest length between vertex_start and vertex_end using BellmanFord algorithm
        
        Args:
            N (int): number of vertices
            M (int): number of edges
            ABC (list): [(ai, bi, ci) for _ in range(N)] where i-th edge is directed from vertex ai to vertex bi and the length is ci 
            vertex_start (int): start vertex. usually use 0.
            vertex_end (int): end vertex. usually use N-1.
            value_if_inf (int or string as you like, optional): value you want when the furthest (or shortest) distance is infinite (or -infinite). Defaults to -1.
            find_shortest (bool, optional): choose False to find furthest path. Defaults to False.
        
        Returns:
            int or string: normally int (but can be str if you set value_if_inf to str)
            
        Example:
                N, M, P = R()
                ABC = [R() for _ in range(M)]
                ABC = [(a-1, b-1, c-P) for a, b, c in ABC]
                print(BellmanFord(N, M, ABC, 0, N-1, value_if_inf = 'inf'))

        """

        def make_reachable_list(N, M, ABC, vertex_start, vertex_end):
            reachable_to_direct = defaultdict(list)
            reachable_from_direct = defaultdict(list)
            reachable_from_start = [False] * N
            reachable_to_end = [False] * N
            reachable_from_start[vertex_start] = True
            reachable_to_end[vertex_end] = True
            reachable_from_both_sides = [False] * N
            dfs_from_start = []
            dfs_to_end = []
            for a, b, c in ABC:
                reachable_to_direct[a].append(b)
                reachable_from_direct[b].append(a)
                if a == vertex_start:
                    dfs_from_start.append(b)
                    reachable_from_start[b] = True
                if b == vertex_end:
                    dfs_to_end.append(a)
                    reachable_to_end[a] = True
            while dfs_from_start:
                v = dfs_from_start.pop()
                for i in reachable_to_direct[v]:
                    if not reachable_from_start[i]:
                        reachable_from_start[i] = True
                        dfs_from_start.append(i)
            while dfs_to_end:
                v = dfs_to_end.pop()
                for i in reachable_from_direct[v]:
                    if not reachable_to_end[i]:
                        reachable_to_end[i] = True
                        dfs_to_end.append(i)
            for i in range(N):
                reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
            return reachable_from_both_sides
        
        reachable_from_both_sides = make_reachable_list(N, M, ABC, vertex_start, vertex_end)
        
        if find_shortest:
            dist = [INF for i in range(N)]
        else:
            dist = [-INF for i in range(N)]
        
        dist[vertex_start] = 0
        for i in range(N):
            updated = False
            for a, b, c in ABC:
                if not reachable_from_both_sides[a]:
                    continue
                elif find_shortest:
                    update_condition = dist[a] + c < dist[b]
                else:
                    update_condition = dist[a] + c > dist[b]
                if dist[a] != INF and update_condition:
                    dist[b] = dist[a] + c
                    updated = True
                    if i == N-1:
                        return value_if_inf
            if not updated:
                break
        return dist[vertex_end]

    
    def warshall_floyd(number_vertex, XYD, shift_one_for_vertex=False):
        
        
        
        
        
        d = [[float("inf")]*number_vertex for i in range(number_vertex)]
        for x, y, dist in XYD:
            if shift_one_for_vertex:
                x = x - 1
                y = y - 1
            d[x][y] = dist
            d[y][x] = dist
        for i in range(number_vertex):
            d[i][i] = 0 
        for k in range(number_vertex):
            for i in range(number_vertex):
                for j in range(number_vertex):
                    d[i][j] = min(d[i][j],d[i][k] + d[k][j])
        return d


    """ initialize variables and set inputs
    
        
        
            
            
    
        
        
        
        
        
        
        
    
        
        
        
        
    
        
        
    """

    
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    r_float = lambda: float(r())
    R = lambda: list(map(int, r().split()))
    R_str = lambda: r().split()
    R_map = lambda: map(int, r().split())
    R_float = lambda: list(map(float, r().split()))
    R_tuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    
    
    
    
    
    
    
    """

    
    if sample_file:
        sys.stdin = open(sample_file)
        
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    N = r_int()
    C = r()
    
    r_cnt = C.count('R')
    w_cnt = C.count('W')
    
    if r_cnt == 0 or w_cnt == 0:
        print(0)
    else:
        w_cnt_mid = C[:r_cnt].count('W')
        print(w_cnt_mid)
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    


    
    
    

    """memo: how to use defaultdict of list
    
    Dic = defaultdict(list)
    
    Dic[x].append(y)
    
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    
    >>> a = 5
    >>> bin_str_a = format(a, '
    >>> print(bin_str_a)
    0b0101 
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Solution (Python):
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
count = 0

N = i()
C = s()

RW = [[0,0] for i in range(N)]
R = 0
W = 0

for i in range(N):
    if C[i] == "W":
        W += 1
    else:
        R += 1
    RW[i][0] = R
    RW[i][1] = W

K = R - RW[R-1][0]
ans = min(K,R,W)
print(ans)

Solution (Python):
N = int(input())
c_list = [s == "R" for s in input().strip()]

count_R = 0
count_W = 0
for s in c_list:
	if s:
		count_R += 1
	else:
		count_W += 1

tobemoved_R = 0
tobemoved_W = 0
for i, s in enumerate(c_list):
	if i < count_R:
		if not s:
			tobemoved_R += 1
	else:
		if s:
			tobemoved_W += 1

print(max(tobemoved_R, tobemoved_W))

Solution (Python):
def d_alter_altar():
    N = int(input())
    C = input()

    left, right = 0, N - 1
    ans = 0
    while left < right:
        if C[left] == 'W' and C[right] == 'W':
            right -= 1
        elif C[left] == 'W' and C[right] == 'R':
            ans += 1
            left += 1
            right -= 1
        elif C[left] == 'R' and C[right] == 'W':
            left += 1
        elif C[left] == 'R' and C[right] == 'R':
            left += 1
    return ans

print(d_alter_altar())

Solution (Python):
import sys












stdin = sys.stdin
sys.setrecursionlimit(10 ** 7)
MIN = -10 ** 9
MOD = 10 ** 9 + 7
INF = float("inf")
IINF = 10 ** 18

def solve():
    n = int(stdin.readline().rstrip())
    c = str(stdin.readline().rstrip())
    
    
    
    
    
    
    ans = 0
    l = 0
    r = -1
    for i in range(n):
        if l-r >= n:
            print(ans)
            exit()
        left = c[l]
        right = c[r]
        if left == "W" and right == "R":
            ans += 1
            l += 1
            r -= 1
        elif left =="W" and right =="W":
            r -= 1
        elif left == "R" and right =="R":
            l += 1
        else:
            l += 1
            r -= 1


if __name__ == '__main__':
    solve()

Solution (Python):
def main():
    n = int(input())
    
    c = list(input())

    wcusum = [0]
    for c_i in c:
        wcusum.append(wcusum[-1]+(1 if c_i == 'W' else 0))

    rinv = [0]
    for c_i in c[::-1]:
        rinv.append(rinv[-1]+(1 if c_i == 'R' else 0))
    rinv = rinv[::-1]

    answers = []

    for i in range(n):
        answers.append(max(wcusum[i],rinv[i+1]))
    print(min(answers))



if __name__ == "__main__":
    main()

Solution (Python):
import sys
import bisect
from functools import lru_cache
from collections import defaultdict
inf = float('inf')
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**6)
def input(): return sys.stdin.readline().rstrip()
def read():
  return int(readline())
def reads():
  return map(int, readline().split())
N=read()
C=input()
red=0
redls=[]
for i,ele in enumerate(C):
    if ele=="R":
        red+=1
        redls.append(i)
redth=0
for i in range(red):
    if C[i]=="R":
        redth+=1   
diff=red-redth
print(diff)

Solution (Python):
import sys

def main():

    input = sys.stdin.readline

    N = int(input())
    c = str(input())[:-1]

    top_index = 0
    bottom_index = N - 1

    ans = 0

    while top_index < bottom_index:
        if(c[top_index] == "W") and (c[bottom_index] == "R"):
            ans += 1
            top_index += 1
            bottom_index -= 1
            continue

        if c[top_index] == "R":
            top_index += 1
        if c[bottom_index] == "W":
            bottom_index -= 1


    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
C = list(input())
l = 0
r = n-1
ans = 0
while l < r:  
  while C[l] == 'R' and l<r:
    l += 1    
  while C[r] == 'W' and l<r:
    r -= 1
  if C[l]=='W' and C[r] == 'R':
    ans += 1
    l += 1
    r -= 1
    
print(ans)

Solution (Python):
n = int(input())
c = input()
l = 0
r = n-1
ans = 0
while l<r:
    while l<n and c[l]=='R':
        l+=1
    while r>=0 and c[r]=='W':
        r-=1
    if l>r:
        break
    ans += 1
    l += 1
    r -= 1
print(ans)

Solution (Python):
N=int(input())
c=list(map(str, input()))

a = c.count('R')

b = c[:a]

d = b.count('R')

print(a-d)

Solution (Python):
N = int(input())
colors = list(input())


sums = [0] * N

if colors[0] == "R":
    sums[0] = 1

for i in range(1,N):
    if colors[i] == "R":
        sums[i] = sums[i-1] + 1
    else:
        sums[i] = sums[i-1]

red_sum = sums[-1]

print(red_sum-sums[red_sum-1])

Solution (Python):
N=int(input())
S=list(input())

num_R=S.count("R")
num_W=S.count("W")

answer=0
for i in range(num_R):
  if S[i]=="W":
    answer+=1
    
print(answer)

Solution (Python):

n = int(input())
A = list(input())
W = A.count("W")
if W == 0:
  print(0)
else:
  ans = A[-W:].count("R")
  print(ans)

Solution (Python):
n = int(input())
C = input()
A = [0]*(n+1)
cnt = 0
for i, c in enumerate(C):
    if c == "R":
        cnt += 1
        A[i+1] = 1
    A[i+1] += A[i]
ans = float("inf")
for i in range(n+1):
    W_l = i - A[i]
    R_r = cnt - A[i]
    temp = min(W_l, R_r) + abs(W_l-R_r)
    ans = min(ans, temp)
print(ans)

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

pos_r = []
pos_w = []
for i in range(n):
    if c[i] == 'R':
        pos_r.append(i)
    else:
        pos_w.append(i)
pos_r.reverse()

ans = 0
m = min(len(pos_r), len(pos_w))
for i in range(m):
    if pos_w[i] < pos_r[i]:
        ans += 1
print(ans)

Solution (Python):
def solve(C,N):
    W,R = [],[]
    for i in range(N):
        if C[i] == "W":
            W.append(i)
        else:
            R.append(i)

    W.sort(reverse = True)
    cnt = 0

    while True:
        if len(W) > 0 and len(R) > 0:
            if W[-1] < R[-1]:
                cnt += 1
                W.pop()
                R.pop()
            else:
                break
        else:
            break

    return cnt

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

    ans = solve(C,N)
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
N=int(input())
C=input()
R=[]
W=[]
for i in range(N):
    if C[i]=='R':
        R.append(i)
    else:
        W.append(i)

R=R[::-1]
r=len(R)
w=len(W)
ans=0
j=0
while j<r and j<w:
    if W[j]<R[j]:
        ans+=1
    j+=1

print(ans)

Solution (Python):


import sys
import math
import time

import collections
from collections import deque
from collections import Counter
import queue
import copy
import bisect
import heapq
import itertools











N = int(input())
c = list(input())
ans = 0
l = 0
r = N-1

while True:
  if(l>=r):
    break
  if(c[l]=="R"):
    l+=1
    continue
  elif(c[r]=="W"):
    r-= 1
    continue
  else:
    l+=1
    r-=1
    ans+=1
    continue

print(ans)

Solution (Python):

input()
c = input()
R = c.count("R")
W = c.count("W")
c2 = "R"*R+"W"*W
r = sum(i!=j and i =="W" for i, j in zip(c,c2))
w = sum(i!=j and i =="R" for i, j in zip(c,c2))
print(min(r,w))

Solution (Python):
n = int(input())
cs = list(input())

c = 0
i = 0
j = n - 1

while True:
   while cs[i] != 'W' and i < j:
      i += 1
   while cs[j] != 'R' and i < j:
      j -= 1
   if i < j:
      cs[i], cs[j] = cs[j], cs[i]
      c += 1
   else:
      break

print(c)

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
Cs = list(input())
from collections import deque
Q = deque()
for i, c in enumerate(Cs):
    if c=='R':
        Q.append(i)

ans = 0
for i in range(N):
    c = Cs[i]
    if c=='W':
        if not Q:
            break
        r = Q.pop()
        if r>i:
            ans += 1
        else:
            break
print(ans)

Solution (Python):
import sys
import math
import collections
import decimal
import itertools
from collections import deque
from functools import reduce
import heapq
import copy
n = int(input())

s = input()


rc = 0
for i in range(n):
    if s[i] == "R":
        rc += 1

wc = 0
for i in range(rc):
    if s[i] == "W":
        wc += 1

print(wc)

Solution (Python):
n = int(input())
lc = input()
lc = lc.lstrip("R").rstrip("W")

ans = 0
lin = 0
rin = len(lc)-1
flg = False
while lin < rin:
    while True:
        if lc[lin] == "W":
            break
        lin += 1
    while True:
        if lc[rin] == "R":
            break
        rin -= 1
    if lin > rin:
        break
    lin += 1
    rin -= 1
    ans += 1

print(ans)

Solution (Python):
a=int(input())
b=list(input())
c=[0]*a
for i in range(a):
  if b[i]=="R":
    c[i]=1
d=sum(c)
print(d-sum(c[:d]))

Solution (Python):
n=int(input())
s=input()
left=0
right=len(s)-1
ans=0
while left<right:
    if s[left]!="W":
        left+=1
    if s[right]!="R":
        right-=1
    if s[left]=="W" and s[right]=="R":
        ans+=1
        left+=1
        right-=1
print(ans)

Solution (Python):
n=int(input())
s=input()
l,r=0,n-1
ans=0
while l<r:
  cnt=0
  while r>=0 and s[r]=='W':r-=1
  while l<n and s[l]=='R':l+=1
  if l>=r:break
  while s[r]=='R':
    cnt+=1
    r-=1
  cm=cnt
  while cnt:
    if s[l]=='W':cnt-=1
    l+=1
    if l>r:break
  ans+=cm-cnt
print(ans)

Solution (Python):
num = int(input())
strs = input()
allRs = 0
notAlignedRs = 0
for i in range(num):
    if strs[i] == 'R':
        allRs += 1
for i in range(allRs):
    if strs[i] == 'W':
        notAlignedRs += 1
print(notAlignedRs)

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

w = 0
w_left = [None]*(N+1)
w_left[0] = 0
for i in range(N):
    if c[i] == 'W': w += 1
    w_left[i+1] = w

r = 0
r_right = [None]*(N+1)
r_right[N] = 0
for i in reversed(range(N)):
    if c[i] == 'R': r += 1
    r_right[i] = r

def cost(i):
    return max(w_left[i], r_right[i])

best = min(cost(i) for i in range(N+1))
print(best)

Solution (Python):
n = int(input())
l = list(input())
cnt_r = l.count('R')
cnt = 0
for i in range(cnt_r,n):
    if l[i] == 'R':
        cnt += 1
print(cnt)

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

right = N - 1
left = 0
ans = 0
flag = False

while True:
  if c[right]=='W':
    if (right>=1)and(right>left+1):
      right -= 1
      continue
    else:
      break
    
  else:
    while True:
      if c[left]=='R':
        if (left<N)and(left<right-1):
          left += 1
          continue
        else:
          flag = True
          break
        
      else:
        ans += 1
        left += 1
        right -= 1
        break
    if flag:
      break
      
print(ans)

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

from collections import Counter

c=Counter(s)

r=c['R']

cnt=0
for i in range(r):
    if s[i]=='W':
        cnt+=1


print(cnt)