The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).

You are given a sequence $a$ consisting of $n$ integers.

You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).

For example, for the sequence $[1, 2, 4, 3, 2]$ the answer is $4$ (you take $1$ and the sequence becomes $[2, 4, 3, 2]$, then you take the rightmost element $2$ and the sequence becomes $[2, 4, 3]$, then you take $3$ and the sequence becomes $[2, 4]$ and then you take $4$ and the sequence becomes $[2]$, the obtained increasing sequence is $[1, 2, 3, 4]$).


-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in $a$.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the $i$-th element of $a$.


-----Output-----

In the first line of the output print $k$ — the maximum number of elements in a strictly increasing sequence you can obtain.

In the second line print a string $s$ of length $k$, where the $j$-th character of this string $s_j$ should be 'L' if you take the leftmost element during the $j$-th move and 'R' otherwise. If there are multiple answers, you can print any.


-----Examples-----
Input
5
1 2 4 3 2

Output
4
LRRR

Input
7
1 3 5 6 5 4 2

Output
6
LRLRRR

Input
3
2 2 2

Output
1
R

Input
4
1 2 4 3

Output
4
LLRR



-----Note-----

The first example is described in the problem statement.

Difficulty: introductory

Starter code:

Solutions:
# AC
import sys


class Main:
    def __init__(self):
        self.buff = None
        self.index = 0

    def __next__(self):
        if self.buff is None or self.index == len(self.buff):
            self.buff = sys.stdin.readline().split()
            self.index = 0
        val = self.buff[self.index]
        self.index += 1
        return val

    def next_int(self):
        return int(next(self))

    def solve(self):
        n = self.next_int()
        x = [self.next_int() for _ in range(0, n)]
        d = 0
        l = 0
        r = n - 1
        rs = []
        while l <= r:
            if x[l] <= d and x[r] <= d:
                break
            if x[l] <= d:
                rs.append('R')
                d = x[r]
                r -= 1
            elif x[r] <= d:
                rs.append('L')
                d = x[l]
                l += 1
            elif x[r] < x[l] or l == r:
                rs.append('R')
                d = x[r]
                r -= 1
            elif x[l] < x[r]:
                rs.append('L')
                d = x[l]
                l += 1
            else:
                ll = l + 1
                while x[ll] > x[ll - 1]:
                    ll += 1
                rr = r - 1
                while x[rr] > x[rr + 1]:
                    rr -= 1
                if ll - l > r - rr:
                    rs.append('L')
                    d = x[l]
                    l += 1
                else:
                    rs.append('R')
                    d = x[r]
                    r -= 1
        print(len(rs))
        print(''.join(rs))


def __starting_point():
    Main().solve()

__starting_point()

from collections import deque
n = int(input())
A = list(map(int, input().split()))
A = deque(A)
ans = ''
last = 0
while len(A) and (A[0] > last or A[-1] > last):
    if len(A) == 1:
        ans += 'R'
        break
    if A[0] > last and A[-1] > last:
        if A[0] < A[-1]:
            last = A[0]
            A.popleft()
            ans += 'L'
        elif A[-1] < A[0]:
            last = A[-1]
            A.pop()
            ans += 'R'
        else:
            lal = last
            cnt1 = -1
            for i in A:
                cnt1 += 1
                if i > lal:
                    lal = i
                else:
                    break
            lol = last
            cnt2 = -1
            for i in range(len(A) - 1, -1, -1):
                cnt2 += 1
                if A[i] > lol:
                    lol = A[i]
                else:
                    break
            if cnt1 > cnt2:
                ans += 'L' * cnt1
            else:
                ans += 'R' * cnt2
            break
    else:
        if A[0] > last:
            last = A[0]
            A.popleft()
            ans += 'L'
        else:
            last = A[-1]
            A.pop()
            ans += 'R'
print(len(ans))
print(ans)


from collections import deque

def solve(A):
    res = []
    last = 0
    while A:
        if max(A[0],A[-1]) <= last:
            return res

        if A[0] == A[-1]:
            v = A[0]-1
            for i,a in enumerate(A):
                if v < a:
                    v = a
                else:
                    break
            else:
                i += 1
            L = i
            v = A[-1]-1
            for i,a in enumerate(reversed(A)):
                if v < a:
                    v = a
                else:
                    break
            else:
                i += 1
            R = i
            _,op = max((L, ['L']*L), (R, ['R']*R))
            res.extend(op)
            return res
        
        v, op = min((v, op) for v,op in ((A[0], 'L'), (A[-1], 'R')) if v > last)
        last = v
        res.append(op)
        if op == 'L':
            A.popleft()
        else:
            A.pop()


def main():
    input()
    A = deque(map(int,input().split()))

    res = solve(A)
    print(len(res))
    print(*res, sep='')


main()

n = int(input())
l = [*map(int, input().split())]
prev = 0
res = []
while l:
    if l[0] == l[-1]:
        if prev >= l[0]: break
        if len(l) <= 2:
            res.append('L')
            break
        c0, c1 = [], []
        p = prev
        for e in l:
            if p < e:
                c0.append('L')
                p = e
            else: break
        p = prev
        for e in l[::-1]:
            if p < e:
                c1.append('R')
                p = e
            else:
                break
        if len(c0) <= len(c1):
            res += c1
        else:
            res += c0
        break
    elif prev < l[0] and (l[0] < l[-1] or prev >= l[-1]):
        i = 0
        res.append('L')
    elif prev < l[-1]: 
        i = -1
        res.append('R')
    else: break
    prev = l[i]
    del l[i]
print(len(res))
print(''.join(res))

3

def check_l(a, l, r):
    d = 0
    last = 0
    while l <= r and a[l] > last:
        last = a[l]
        l += 1
        d += 1
    return d

def check_r(a, l, r):
    d = 0
    last = 0
    while l <= r and a[r] > last:
        last = a[r]
        r -= 1
        d += 1
    return d

def main():
    # skip N
    input()
    a = [int(x) for x in input().split(' ')]
    n = len(a)

    l, r = 0, n - 1
    res = []
    
    last = 0
    picked = True

    while l <= r and picked:
        picked = False
        if last < a[l] and last < a[r]:
            if a[l] < a[r]:
                last = a[l]
                res.append('L')
                l += 1
            elif a[l] == a[r]:
                dl = check_l(a, l, r)
                dr = check_r(a, l, r)
                
                if dl > dr:
                    res.extend(['L'] * dl)
                    last = a[l + dl - 1]
                    l += dl
                else:
                    res.extend(['R'] * dr)
                    last = a[r - dr + 1]
                    r -= dr
            else:
                last = a[r]
                res.append('R')
                r -= 1
            picked = True
            continue
        
        if last < a[l]:
            last = a[l]
            res.append('L')
            l += 1
            picked = True
            continue
        
        if last < a[r]:
            last = a[r]
            res.append('R')
            r -= 1
            picked = True
            continue
    
    print(len(res))
    print("".join(res))
        

def __starting_point():
    main()
__starting_point()

n = int(input())
ai = list(map(int,input().split()))
ans = 0
ans2 = ""
num = 0
left = 0
right = n-1
flag = 0
for i in range(n):
    if ai[left] <= num:
        if ai[right] <= num:
            break
        num = ai[right]
        ans += 1
        right -= 1
        ans2 += "R"
        continue
        
    if ai[right] <= num:
        if ai[left] <= num:
            break
        num = ai[left]
        ans += 1
        left += 1
        ans2 += "L"
        continue
    if ai[left] > ai[right]:
        num = ai[right]
        ans += 1
        right -= 1
        ans2 += "R"
    elif ai[left] == ai[right]:
        if left == right:
            ans += 1
            ans2 += "L"
            break
        flag = 1
        break
    else:
        num = ai[left]
        ans += 1
        left += 1
        ans2 += "L"
if flag == 1:
    left2 = left
    temp = 0
    num2 = num
    while left2 < right:
        if ai[left2] > num2:
            temp += 1
            num2 = ai[left2]
        else:
            break
        left2 += 1
    temp2 = 0
    right2 = right
    num2 = num
    while right2 > left:
        if ai[right2] > num2:
            temp2 += 1
            num2 = ai[right2]
        else:
            break
        right2 -= 1
    if temp >= temp2:
        ans += temp
        ans2 += "L" * temp
    else:
        ans += temp2
        ans2 += "R" * temp2
print(ans)
print(ans2)


n=int(input())
arr=list(map(int,input().split()))
i=0
j=n-1
ans=''
prev=0
while(i<j):
	if(arr[i]<arr[j]):
		if(arr[i]>prev):
			ans+='L'
			prev=arr[i]
			i+=1
		elif(arr[j]>prev):
			ans+='R'
			prev=arr[j]
			j-=1
		else:
			break
	elif(arr[i]>arr[j]):
		if(arr[j]>prev):
			ans+='R'
			prev=arr[j]
			j-=1
		elif(arr[i]>prev):
			ans+='L'
			prev=arr[i]
			i+=1
		else:
			break
	else:
		#print(prev)
		if(arr[i]<prev):
			break
		else:
			count1=0
			count2=0
			temp=i
			temprev=prev
			while(temp<j):
				if(arr[temp]>temprev):
					temprev=arr[temp]
					count1+=1
					temp+=1
				else:
					break
			temp=j
			temprev2=prev
			#print(count1)
			while(temp>i):
				#print(arr[temp],prev)
				if(arr[temp]>temprev2):
					temprev2=arr[temp]
					count2+=1
					temp-=1
				else:
					break
			#print(count1,count2)
			if(count1>=count2):
				ans+='L'*count1
				i+=count1
				prev=temprev
			elif(count2>count1):
				ans+='R'*count2
				j-=count2
				prev=temprev2
			break

	#print(ans)
	#print(i,j)
if(i==j and arr[i]>prev):
	ans+='R'
	prev=arr[i]
print(len(ans))
print(ans)



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

"""Codeforces Round #555 (Div. 3)

Problem C. Increasing Subsequence

:author:         Kitchen Tong
:mail:    kctong529@gmail.com

Please feel free to contact me if you have any question
regarding the implementation below.
"""

__version__ = '1.0'
__date__ = '2019-04-26'

import sys


def rec_solve(a, l, r, last):
    choices = []
    while l <= r:
        if a[l] == a[r] and a[l] > last:
            sub_ans_1 = rec_solve(a, l+1, r, a[l])
            sub_ans_2 = rec_solve(a, l, r-1, a[l])
            if len(sub_ans_1) > len(sub_ans_2):
                choices.append('L')
                choices += sub_ans_1
                return choices
            else:
                choices.append('R')
                choices += sub_ans_2
                return choices
        elif a[l] < a[r] and a[l] > last:
            last = a[l]
            choices.append('L')
            l += 1
        elif a[r] > last:
            last = a[r]
            choices.append('R')
            r -= 1
        elif a[l] > last:
            last = a[l]
            choices.append('L')
            l += 1
        else:
            return choices
    return choices

def solve(n, a):
    return rec_solve(a, 0, n-1, 0)

def main(argv=None):
    n = int(input())
    a = list(map(int, input().split()))
    choice = solve(n, a)
    print(len(choice))
    print(''.join(choice))
    return 0

def __starting_point():
    STATUS = main()
    return(STATUS)


__starting_point()


n = int(input())

arr = list(map(int,input().strip().split()))

fl = 1

ans = ""
c = 0

st = 0
en = n-1

la = 0
floop = 0
while fl:
    if st>=n or en<=-1:
        
        break

    if arr[st]==arr[en]:
        floop =1
        break;

    
    if arr[st] > la:
        if arr[en]>la:
            if arr[en] > arr[st]:
                st+=1
                la = arr[st-1]
                ans+="L"
                c+=1
            else:
                en-=1
                la  = arr[en+1]
                ans+="R"
                c+=1
        else:
            st+=1
            la = arr[st-1]
            ans+="L"
            c+=1
    else:
        if arr[en]>la:
            en-=1
            la =arr[en+1]
            ans+="R"
            c+=1
        else:
            break;
#print(floop)
if floop == 1:
    orig = la
    cm = 0
    s1 = ""
    for i in range(st,en+1):
        if arr[i]>la:
            la = arr[i]
            cm+=1
            s1+="L"
        else:
            break;
    cn = 0
    s2 = ""
    la = orig
    for i in range(en,st-1,-1):
        if la < arr[i]:
            cn+=1
            s2+="R"
            la = arr[i]
        else:
            break;
    if cn>cm:
        ans+=s2
    else:
        
        ans+=s1
    c+=max(cn,cm)
    ##print(s1,s2)

    
    
print(c)
print(ans)
                


n = int(input())
a = [int(i) for i in input().split()]
last = -1
i = 0
j = n - 1
ans = ''
while i <= j:
    if max(a[i], a[j]) <= last:
        break
    if a[i] == a[j]:
        start = i
        k = 0
        last = a[i]
        i += 1
        while i <= j:
            if a[i] <= last:
                break
            else:
                last = a[i]
                k += 1
                i += 1
        last = a[j]
        k2 = 0
        i = start
        j -= 1
        while i <= j:
            if a[j] <= last:
                break
            else:
                last = a[j]
                k2 += 1
                j -= 1
        if k > k2:
            ans += 'L' * (k + 1)
        else:
            ans += 'R' * (k2 + 1)
        break
    if a[i] < a[j]:
        if a[i] > last:
            ans += 'L'
            last = a[i]
            i += 1
        else:
            ans += 'R'
            last = a[j]
            j -= 1
    else:
        if a[j] > last:
            ans += 'R'
            last = a[j]
            j -= 1
        else:
            ans += 'L'
            last = a[i]
            i += 1
print(len(ans))
print(ans)


def search(l, r, pr):
	posl = ""
	fl = True
	while l <= r:
		if sp[l] < sp[r]:
			if sp[l] > pr:
				pr = sp[l]
				l += 1
				posl += "L"
			elif sp[r] > pr:
				pr = sp[r]
				r -= 1
				posl += "R"
			else:
				fl = False
		elif sp[l] > sp[r]:
			if sp[r] > pr:
				pr = sp[r]
				r -= 1
				posl += "R"
			elif sp[l] > pr:
				pr = sp[l]
				l += 1
				posl += "L"
			else:
				fl = False
		else:
			if sp[l] > pr:
				fst = search(l + 1, r, sp[l]) + "L"
				sec = search(l, r - 1, sp[r]) + "R"
				if len(sec) > len(fst):
					posl += sec
				else:
					posl += fst
			fl = False
		if not fl:
			break
	return posl



n = int(input())
sp = list(map(int, input().split()))
pr = 0
posl = ""
l = 0
r = n - 1
new = search(l, r, 0)
print(len(new))
print(new)



import sys
input = sys.stdin.readline
#from collections import deque

n=int(input())
A=list(map(int,input().split()))
#B=deque(A)


LIST=[1]*n
LIST_INV=[1]*n

for i in range(n-2,-1,-1):
    if A[i]<A[i+1]:
        LIST[i]=LIST[i+1]+1


for i in range(1,n):
    if A[i]<A[i-1]:
        LIST_INV[i]=LIST_INV[i-1]+1

ANS=[]
SCORE=0
i=0
j=n-1
while True:
    if i==j and A[i]>SCORE:
        ANS.append("R")
        SCORE=A[i]
        break
    
    if A[i]>A[j] and A[j]>SCORE:
        ANS.append("R")
        SCORE=A[j]
        j-=1
        
    elif A[i]<A[j] and A[i]>SCORE:
        ANS.append("L")
        SCORE=A[i]
        i+=1
        
    elif A[i]>A[j] and A[j]<=SCORE and A[i]>SCORE:
        ANS.append("L")
        SCORE=A[i]
        i+=1
        
    elif A[i]<A[j] and A[i]<=SCORE and A[j]>SCORE:
        ANS.append("R")
        SCORE=A[j]
        j-=1

    elif A[i]==A[j] and A[i]>SCORE:
        if LIST[i]>LIST_INV[j]:
            ANS.append("L")
            SCORE=A[i]
            i+=1
        else:
            ANS.append("R")
            SCORE=A[j]
            j-=1

    else:
        break
print(len(ANS))
print("".join(ANS))            
            
    
    


n = int(input())
a = [int(item) for item in input().split()]

s = []
i = 0
j = n - 1
ans = []
while i <= j:
    if a[i] < a[j]:
        if not s or s[-1] < a[i]:
            s.append(a[i])
            ans.append('L')
            i += 1
        elif not s or s[-1] < a[j]:
            s.append(a[j])
            ans.append('R')
            j -= 1
        else:
            break
    elif a[i] > a[j]:
        if not s or s[-1] < a[j]:
            ans.append('R')
            s.append(a[j])
            j -= 1
        elif not s or s[-1] < a[i]:
            s.append(a[i])
            ans.append('L')
            i += 1
        else:
            break
    else:
        p1 = 0
        p2 = 0
        cur_last = s[-1] if s else None
        or_i = i
        while i <= j and (cur_last is None or a[i] > cur_last):
            cur_last = a[i]
            i += 1
            p1 += 1

        cur_last = s[-1] if s else None
        while or_i <= j and (cur_last is None or a[j] > cur_last):
            cur_last = a[j]
            j -= 1
            p2 += 1
        if p1 > p2:
            ans += list("L" * p1)
        else:
            ans += list("R" * p2)
        break

print(len(ans))
print(''.join(str(x) for x in ans))



n = int(input())

M = list(map(int, input().split()))
L = [1] * n
R = [1] * n

for i in range(1, len(M)):
    if M[i] < M[i-1]:
        R[i] = R[i-1] + 1
    if M[n - 1 - i] < M[n - i]:
        L[n-1-i] = L[n-i] + 1

         
        
#print(L)
#print(R)        
ans = []

last = -1
l, r = 0, n - 1

while r >= l:
    #print(str(l) + ' ' + str(r), end=': ')
    #print(last)
    if M[r] <= last and M[l] <= last:
        break
    if M[r] == M[l]:
       
        if L[l] > R[r]:
            ans += ["L"]
            last = M[l]
            l += 1
        else:
            ans += ["R"]
            last = M[r]
            r -= 1
    elif M[r] <= last:
        last = M[l]
        ans += ["L"]
        l += 1
    elif M[l] <= last:
        last = M[r]
        ans += ["R"]
        r -= 1
    else:
        if M[l] < M[r]:
            last = M[l]
            ans += ["L"]
            l += 1
        else:
            last = M[r]
            ans += ["R"]
            r -= 1

print(len(ans))
print("".join(ans))


R = lambda: map(int, input().split())


def isL():
    k1 = 1
    while i + k1 <= j and a[i+k1]>a[i+k1-1]:
        k1 += 1
    k2 = 1
    while j - k2 >= i and a[j-k2]>a[j-k2+1]:
        k2 += 1
    return k1 >= k2


n, a = int(input()), list(R())
res = []
i, j = 0, n-1
v = 0
while i <= j:
    if a[i] <= v and a[j] <= v:
        break
    elif a[i] > v >= a[j]:
        res.append('L')
        v = a[i]
        i += 1
    elif a[j] > v >= a[i]:
        res.append('R')
        v = a[j]
        j -= 1
    elif a[i] < a[j]:
        res.append('L')
        v = a[i]
        i += 1
    elif a[j] < a[i]:
        res.append('R')
        v = a[j]
        j -= 1
    elif i == j:
        res.append('L')
        v = a[i]
        i += 1
    elif isL():
        res.append('L')
        v = a[i]
        i += 1
    else:
        res.append('R')
        v = a[j]
        j -= 1

res = ''.join(res)
print(len(res))
print(res)

n = int(input())
sl = list(map(int, input().split()))
ans = ""
current = 0
for i in range(n):
    if(current<sl[0] and current<sl[-1]):
        #print(sl)
        if(sl[0] == sl[-1] and i!=(n-1)):
            l, r = 1, 1
            for j in range(len(sl)):
                #print(sl[j], sl[j+1])
                if(sl[j]<sl[j+1]): l += 1
                else: break
            for j in range(len(sl)):
                #print(sl[-(j+1)], sl[-(j+2)], sl[-(j+1)]>sl[-(j+2)])
                if(sl[-(j+1)]<sl[-(j+2)]): r += 1
                else: break
            #print(l, r)
            if(l>r): ans += "L"*l
            else: ans += "R"*r
            break
        elif(current<sl[0] and sl[0] <= sl[-1]):
            ans += "L"
            current = sl.pop(0)
        elif(current<sl[-1] and sl[0]>sl[-1]):
            ans += "R"
            current = sl.pop()
    elif(current<sl[0] and current>=sl[-1]):
        ans += "L"
        current = sl.pop(0)
    elif(current>=sl[0] and current<sl[-1]):
        ans += "R"
        current = sl.pop()
    else: break
print(len(ans))
print(ans)

# -*- coding: utf-8 -*-
"""
@Project : CodeForces
@File    : 32.py 
@Time    : 2019/4/26 23:43
@Author  : Koushiro 
"""

def __starting_point():
    n = int(input())
    nums = list(map(int, input().split()))
    result = []
    last = -1
    left = 0
    right = len(nums) - 1
    while left <= right:
        if nums[left] < nums[right]:
            if nums[left] > last:
                last = nums[left]
                left += 1
                result.append('L')
            elif nums[right] > last:
                last = nums[right]
                right -= 1
                result.append('R')
            else:
                break
        elif nums[left] > nums[right]:
            if nums[right] > last:
                last = nums[right]
                right -= 1
                result.append('R')
            elif nums[left] > last:
                last = nums[left]
                left += 1
                result.append('L')
            else:
                break
        elif nums[left] == nums[right]:
            l_n = left
            r_n = right
            l_c = 0
            r_c = 0
            l_last = last
            r_last = last
            while l_n <= right:
                if nums[l_n] > l_last:
                    l_c += 1
                    l_last = nums[l_n]
                    l_n += 1
                else:
                    break
            while r_n >= left:
                if nums[r_n] > r_last:
                    r_c += 1
                    r_last = nums[r_n]
                    r_n -= 1
                else:
                    break
            if l_c > r_c:
                for i in range(l_c):
                    result.append("L")
            else:
                for i in range(r_c):
                    result.append("R")
            break

    print(len(result))
    print("".join(result))

__starting_point()

n = int(input())
nums = list(map(int, input().split()))


def foo(l, r, prev=0):
    ans = ""
    while l <= r:
        if nums[l] <= prev and nums[r] <= prev:
            break
        if prev < nums[l] < nums[r]:
            ans += "L"
            prev = nums[l]
            l += 1
        elif prev < nums[r] < nums[l]:
            ans += "R"
            prev = nums[r]
            r -= 1
        elif nums[r] > nums[l]:
            ans += "R"
            prev = nums[r]
            r -= 1
        elif nums[r] < nums[l]:
            ans += "L"
            prev = nums[l]
            l += 1
        elif l == r:
            ans += 'R'
            break
        else:
            a1 = 'L' + foo(l + 1, r, nums[l])
            a2 = 'R' + foo(l, r - 1, nums[l])
            ans += a1 if len(a1) > len(a2) else a2
            break
    return ans


ans = foo(0, n - 1)
print(len(ans))
print(ans)


from collections import deque
n=int(input())
a=deque([int(x) for x in input().split()])
cur=-1
ans=''
while (cur<a[0] or cur<a[-1]):
    if a[0]<a[-1]:
        if cur<a[0]:
            ans+='L'
            cur=a[0]
            a.popleft()
        else:
            ans+='R'
            cur=a[-1]
            a.pop()
        
    elif a[0]>a[-1]:
        if cur<a[-1]:
            ans+='R'
            cur=a[-1]
            a.pop()
        else:
            ans+='L'
            cur=a[0]
            a.popleft()
    elif len(a)==1:
        ans+='R'
        cur=a[-1]
        a.pop()
    elif a[0]==a[-1]:
        cur1=cur
        cur2=cur
        b=a.copy()
        c=a.copy()
        count1=0
        count2=0
        while cur1<b[0]:
            count1+=1
            cur1=b[0]
            b.popleft()
        while cur2<c[-1]:
            count2+=1
            cur2=c[-1]
            c.pop()
        if count1>count2:
            for i in range(count1):
                ans+='L'
            break
        else:
            for i in range(count2):
                ans+='R'
            break
            
    if len(a)==0:
        break

print(len(ans))
print(ans)

''' CODED WITH LOVE BY SATYAM KUMAR '''

from sys import stdin, stdout
import cProfile, math
from collections import Counter,defaultdict,deque
from bisect import bisect_left,bisect,bisect_right
import itertools
from copy import deepcopy
from fractions import Fraction
import sys, threading
import operator as op
from functools import reduce
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**27)  # new thread will get stack of such size
fac_warmup = False
printHeap = str()
memory_constrained = False
P = 10**9+7
import sys

class merge_find:
    def __init__(self,n):
        self.parent = list(range(n))
        self.size = [1]*n
        self.num_sets = n
        self.lista = [[_] for _ in range(n)]
    def find(self,a):
        to_update = []
        while a != self.parent[a]:
            to_update.append(a)
            a = self.parent[a]
        for b in to_update:
            self.parent[b] = a
        return self.parent[a]
    def merge(self,a,b):
        a = self.find(a)
        b = self.find(b)
        if a==b:
            return
        if self.size[a]<self.size[b]:
            a,b = b,a
        self.num_sets -= 1
        self.parent[b] = a
        self.size[a] += self.size[b]
        self.lista[a] += self.lista[b]
    def set_size(self, a):
        return self.size[self.find(a)]
    def __len__(self):
        return self.num_sets

def display(string_to_print):
    stdout.write(str(string_to_print) + "\n")

def primeFactors(n): #n**0.5 complex 
    factors = dict()
    for i in range(2,math.ceil(math.sqrt(n))+1):  
        while n % i== 0: 
            if i in factors:
                factors[i]+=1
            else: factors[i]=1
            n = n // i 
    if n>2:
        factors[n]=1
    return (factors)

def all_factors(n):    
    return set(reduce(list.__add__, 
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

def fibonacci_modP(n,MOD):
    if n<2: return 1
    #print (n,MOD)
    return (cached_fn(fibonacci_modP, (n+1)//2, MOD)*cached_fn(fibonacci_modP, n//2, MOD) + cached_fn(fibonacci_modP, (n-1) // 2, MOD)*cached_fn(fibonacci_modP, (n-2) // 2, MOD)) % MOD

def factorial_modP_Wilson(n , p): 
    if (p <= n): 
        return 0
    res = (p - 1) 
    for i in range (n + 1, p): 
        res = (res * cached_fn(InverseEuler,i, p)) % p 
    return res 

def binary(n,digits = 20):
    b = bin(n)[2:]
    b = '0'*(20-len(b))+b
    return b

def isprime(n):
    """Returns True if n is prime."""
    if n < 4:
        return True
    if n % 2 == 0:
        return False
    if n % 3 == 0:
        return False
    i = 5
    w = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += w
        w = 6 - w
    return True
factorial_modP = []
def warm_up_fac(MOD):
    nonlocal factorial_modP,fac_warmup
    if fac_warmup: return
    factorial_modP= [1 for _ in range(fac_warmup_size+1)]
    for i in range(2,fac_warmup_size):
        factorial_modP[i]= (factorial_modP[i-1]*i) % MOD
    fac_warmup = True

def InverseEuler(n,MOD):
    return pow(n,MOD-2,MOD)

def nCr(n, r, MOD):
    nonlocal fac_warmup,factorial_modP
    if not fac_warmup:
        warm_up_fac(MOD)
        fac_warmup = True
    return (factorial_modP[n]*((pow(factorial_modP[r], MOD-2, MOD) * pow(factorial_modP[n-r], MOD-2, MOD)) % MOD)) % MOD

def test_print(*args):
    if testingMode:
        print(args)

def display_list(list1, sep=" "):
    stdout.write(sep.join(map(str, list1)) + "\n")

def display_2D_list(li):
    for i in li:
        print(i)
def prefix_sum(li):
    sm = 0
    res = []
    for i in li:
        sm+=i
        res.append(sm)
    return res

def get_int():
    return int(stdin.readline().strip())

def get_tuple():
    return map(int, stdin.readline().split())

def get_list():
    return list(map(int, stdin.readline().split()))
import heapq,itertools
pq = []                         # list of entries arranged in a heap
entry_finder = {}               # mapping of tasks to entries
REMOVED = '<removed-task>' 
def add_task(task, priority=0):
    'Add a new task or update the priority of an existing task'
    if task in entry_finder:
        remove_task(task)
    count = next(counter)
    entry = [priority, count, task]
    entry_finder[task] = entry
    heapq.heappush(pq, entry)

def remove_task(task):
    'Mark an existing task as REMOVED.  Raise KeyError if not found.'
    entry = entry_finder.pop(task)
    entry[-1] = REMOVED

def pop_task():
    'Remove and return the lowest priority task. Raise KeyError if empty.'
    while pq:
        priority, count, task = heapq.heappop(pq)
        if task is not REMOVED:
            del entry_finder[task]
            return task
    raise KeyError('pop from an empty priority queue')
memory = dict()
def clear_cache():
    nonlocal memory
    memory = dict()
def cached_fn(fn, *args):
    nonlocal memory
    if args in memory:
        return memory[args]
    else:
        result = fn(*args)
        memory[args] = result
        return result

def ncr (n,r):
    return math.factorial(n)/(math.factorial(n-r)*math.factorial(r))
def binary_serach(i,li):
    #print("Search for ",i)
    fn = lambda x: li[x]-x//i
    x = -1
    b = len(li)
    while b>=1:
        #print(b,x)
        while b+x<len(li) and fn(b+x)>0: #Change this condition 2 to whatever you like
            x+=b
        b=b//2
    return x

# -------------------------------------------------------------- MAIN PROGRAM
TestCases = False
testingMode = False
fac_warmup_size = 10**5+100
optimiseForReccursion = True #Can not be used clubbed with TestCases # WHen using recursive functions, use Python 3
from math import factorial

def main():
    get_int()
    li = deque(get_list())
    prev = 0
    res = []
    while len(li)>0:
        if li[0]==li[-1] and li[0]>prev and len(li)>1:
            guess1 = 0
            guess2 = 0
            prev = li[0]
            p = prev
            dq = list(li)
            n = len(dq)
            for i in range(1,n):
                if dq[i]>prev: prev=dq[i]
                else: break
                if i==n-1: i=n
            guess1 = i
            dq.reverse()
            prev = p
            for i in range(1,n):
                if dq[i]>prev: prev=dq[i]
                else: break
                if i==n-1: i=n
            guess2 = i
            if guess1>guess2:
                res += ["L"]*guess1
            else:
                res += ["R"]*guess2
            break

        elif li[0]<li[-1] and li[0]>prev:
            prev = li.popleft()
            res.append("L")     
        elif li[-1]>prev:
            prev = li.pop()
            res.append("R")
        elif li[0]>prev:
            prev = li.popleft()
            res.append("L") 
        else: break
    print(len(res))
    display_list(res,"")

# --------------------------------------------------------------------- END=


if TestCases: 
    for i in range(get_int()): 
        cProfile.run('main()') if testingMode else main(i) 
else: (cProfile.run('main()') if testingMode else main()) if not optimiseForReccursion else threading.Thread(target=main).start()

N = int(input())
a_list = list(map(int, input().split()))
from collections import deque
import bisect

deq = deque(a_list)
ans = ""
left = 0
right = 0
min_num = -1
cnt = 0
f = False
lr = False
while len(deq) >= 2:
    left = deq.popleft()
    right = deq.pop()
    # print(left, right)
    max_num = max(left, right)
    if max_num > min_num:

        if left == right:
            deq.appendleft(left)
            deq.append(right)
            lr = True
            break
        cnt += 1
        if right > left > min_num:
            ans += "L"
            deq.append(right)
            min_num = left
        elif left > right > min_num:
            ans += "R"
            deq.appendleft(left)
            min_num = right
        elif left > min_num:
            ans += "L"
            deq.append(right)
            min_num = left
        else:
            ans += "R"
            deq.appendleft(left)
            min_num = right
    else:
        f = True
        break
if lr:
    l = 0
    r = 0
    tmp = deq.copy()
    prv = -1
    for t in tmp:
        if t > prv:
            l += 1
        else:
            break
        prv = t
    tmp = list(reversed(tmp))
    prv = -1
    for t in tmp:
        if t > prv:
            r += 1
        else:
            break
        prv = t
    if l > r:
        print(cnt + l)
        print(ans + "L" * l)
    else:
        print(cnt + r)
        print(ans + "R" * r)
    return


if f:
    print(cnt)
    print(ans)
else:
    tmp = deq.pop()
    if tmp > min_num:
        cnt += 1
        print(cnt)
        print(ans + "R")
    else:
        print(cnt)
        print(ans)


n = int(input())
a = [int(i) for i in input().split()]
new = [0]
s = ''
i = 0
j = -1

def rec(a, i, j):
    c = func(a, i + 1, j, new + [a[i]], s)
    d = func(a, i, j - 1, new + [a[j]], s)
    if c[0] < d[0]:
        return True
    else:
        return False

def func(a, i, j, new, s):
    while True:
        if n - i < -j:
            return len(new) - 1, s
            break
        if a[i] > new[-1] and a[j] > new[-1]:
            if a[i] == a[j]:
                if rec(a, i, j):
                    new.append(a[j])
                    j -= 1
                    s += 'R'
                else:
                    s += 'L'
                    new.append(a[i])
                    i += 1
            elif a[i] < a[j]:
                new.append(a[i])
                s += 'L'
                i += 1
            else:
                new.append(a[j])
                s += 'R'
                j -= 1
        elif a[i] > new[-1] or a[j] > new[-1]:
            if a[i] > new[-1]:
                new.append(a[i])
                s += 'L'
                i += 1
            else:
                new.append(a[j])
                s += 'R'
                j -= 1
        else:
            return len(new) - 1, s
            break

for j in func(a, i, j, new, s):
    print(j)


def solve(p, q, r):
    ans = ""
    current = r
    i = p
    j = q
    while True:
        if j < i:
            break
        if current < num[i] < num[j] or num[j] <= current < num[i]:
            ans += "L"
            current = num[i]
            i += 1
            continue
        if current < num[j] < num[i] or num[i] <= current < num[j]:
            ans += "R"
            current = num[j]
            j -= 1
            continue
        if current < num[i] == num[j]:
            ans1 = solve(i, j - 1, num[i])
            ans2 = solve(i + 1, j, num[i])
            if len(ans1) > len(ans2):
                ans += "R" + ans1
            else:
                ans += "L" + ans2
        break
    return ans

n = int(input())
num = [*list(map(int, input().split()))]
ans = solve(0, n - 1, -1)
print(len(ans))
print(ans)


def main():
    n = int(input())
    a = list(map(int, input().split()))
    i = 0
    j = n - 1
    last = -1
    anz = []
    stop = False
    while i != j:
        if a[i] == a[j]:
            stop = True
            break
        if a[i] < a[j]:
            if a[i] > last:
                last = a[i]
                i += 1
                anz.append("L") 
            elif a[j] > last:
                last = a[j]
                j -= 1
                anz.append("R")
            else:
                break
        else:
            if a[j] > last:
                last = a[j]
                j -= 1
                anz.append("R") 
            elif a[i] > last:
                last = a[i]
                i += 1
                anz.append("L")
            else:
                break
    if i == j and a[i] > last:
        anz.append("R")
    if stop:
        l = []
        r = []
        i1 = i
        last1 = last
        while last1 < a[i] and i != j:
            last1 = a[i]
            i += 1
            l.append("L")
        while last < a[j] and i1 != j:
            last = a[j]
            j -= 1
            r.append("R")
        if len(l) > len(r):
            print(len(anz) + len(l))
            for elem in anz:
                print(elem, end="")
            for elem in l:
                print(elem, end="")
        else:
            print(len(r) + len(anz))
            for elem in anz:
                print(elem, end="")
            for elem in r:
                print(elem, end="")            
    else:
        print(len(anz))
        for elem in anz:
            print(elem, end="")
main()