This is the hard version of the problem. The difference between the versions is that in the easy version all prices $a_i$ are different. You can make hacks if and only if you solved both versions of the problem.

Today is Sage's birthday, and she will go shopping to buy ice spheres. All $n$ ice spheres are placed in a row and they are numbered from $1$ to $n$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.

An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.

You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.


-----Input-----

The first line contains a single integer $n$ $(1 \le n \le 10^5)$ — the number of ice spheres in the shop.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^9)$ — the prices of ice spheres.


-----Output-----

In the first line print the maximum number of ice spheres that Sage can buy.

In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.


-----Example-----
Input
7
1 3 2 2 4 5 4

Output
3
3 1 4 2 4 2 5 


-----Note-----

In the sample it's not possible to place the ice spheres in any order so that Sage would buy $4$ of them. If the spheres are placed in the order $(3, 1, 4, 2, 4, 2, 5)$, then Sage will buy one sphere for $1$ and two spheres for $2$ each.

Difficulty: interview

Starter code:

Solutions:
import sys
input = sys.stdin.readline

n = int(input())
x = sorted(list(map(int, input().split())))
a, b = x[:n//2], x[n//2:]
tmp = []
for i in range(n//2):
    tmp.append(b[i])
    tmp.append(a[i])
if n % 2:
    tmp.append(b[-1])
cnt = 0
for i in range(1, n-1, 2):
    if tmp[i+1] > tmp[i] < tmp[i-1]:
        cnt += 1
print(cnt)
print(*tmp)

n=int(input())
a=list(map(int,input().split()))
a.sort()
ans=[0]*n
for i in range(n//2):
  ans[1+i*2]=a[i]
for i in range(n//2,n):
  ans[(i-n//2)*2]=a[i]
co=0
for i in range(1,n-1):
  if ans[i-1]>ans[i] and ans[i]<ans[i+1]:co+=1
print(co)
print(*ans)

n = int(input())
a = sorted(map(int, input().split()))
b = [0] * n
b[1::2], b[::2] = a[:n//2], a[n//2:]
print(sum(b[i-1] > b[i] < b[i+1] for i in range(1, n - 1)))
print(*b)


n=int(input())
a=sorted(map(int,input().split()))
l=[a[(1-i%2)*(n//2)+i//2]for i in range(n)]
c=0
for i in range(1,n-1):
 if l[i-1]>l[i]<l[i+1]:c+=1
print(c)
print(' '.join(map(str,l)))

N = int(input())
List = [int(x) for x in input().split()]
List.sort()
count = 0
arr = [0] * N
index = 0
for i in range(1,N,2):
    arr[i] = List[index]
    index += 1
for i in range(0,N,2):
    arr[i] = List[index]
    index += 1
count = 0
for i in range(1,N-1):
    if(arr[i]<arr[i-1] and arr[i]<arr[i+1]):
        count+=1
print(count)
print(*arr)


n = int(input())
a = list(map(int, input().split()))
a.sort()
lo = 0
hi = (n+1)//2
while hi - lo > 1:
    test = (hi + lo)//2
    smol = a[:test]
    large = a[-test-1:]
    rest = a[test:-test-1]
    works = True
    for i in range(test):
        if smol[i] == large[i] or smol[i] == large[i+1]:
            works = False
    if works:
        lo = test
    else:
        hi = test
smol = a[:lo]
large = a[-lo-1:]
rest = a[lo:-lo-1]
o = []
while smol:
    o += [large.pop()]
    o += [smol.pop()]
o += large
o += rest
print(lo)
print(' '.join(map(str,o)))


# Fast IO (be careful about bytestring, not on interactive)

# import os,io
# input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

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

a.sort()
b = [0] * n
for i in range((n + 1) // 2 - 1):
    b[2 * i + 1] = a[i]
if n % 2 == 0:
    b[n - 1] = a[n // 2 - 1]
for i in range((n + 1) // 2 - n % 2 ,n):
    b[2 * i - 2 * ((n + 1) // 2 - n % 2)] = a[i]
cnt = 0
for i in range(n):
    if i > 0 and i < n-1 and b[i] < b[i - 1] and b[i] < b[i + 1]:
        cnt += 1 
print(cnt)
print(" ".join(map(str,b)))

n = int(input())
A = [int(x) for x in input().split()]
A.sort()
R = [None]*n

R[1::2] = A[:n//2]
R[0::2] = A[n//2:]
r = 0
for i in range(1,n-1):
    r += R[i-1] > R[i] < R[i+1];
print(r)
print(*R)


n = int(input())
a = list(map(int,input().split()))
a = sorted(a)
x = a[:n//2]
a = a[n//2:]
l,k,m = [],0,0
for i in range(n):
     if i%2==0:
          l.append(a[k])
          k+=1
     else:
          l.append(x[m])
          m+=1
m=0
for i in range(1,n-1):
     if(l[i]<l[i-1] and l[i]<l[i+1]):
          m+=1
print(m)   
for i in l:
     print(i,end=" ")

n = int(input())
arr = list(map(int, input().split()))
res = [0] * n
arr.sort()
for i in range(n):
    if i < n//2:
        res[i*2+1] = arr[i]
    else:
        res[(i-n//2)*2] = arr[i]

x = 0
for i in range(1, n-1):
    if res[i-1] > res[i] < res[i+1]:
        x += 1
print(x)
print(*res)


import sys
input = sys.stdin.readline


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

res = [0] * n
a = sorted(a, reverse=True)
ai = 0

for i in range(0, n, 2):
    res[i] = a[ai]
    ai += 1
if n % 2 == 0:
    res[-1] = a[ai]
    ai += 1
for i in range(1, n - 1, 2):
    res[i] = a[ai]
    ai += 1

ans = 0
for i in range(n):
    if not(i - 1 >= 0 and i + 1 < n):
        continue
    if res[i] < res[i - 1] and res[i] < res[i + 1]:
        ans += 1
print(ans)
print(*res)

from collections import defaultdict as dd
import math
import sys
import heapq
import copy
input=sys.stdin.readline
def nn():
	return int(input())

def li():
	return list(input())

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

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


def solve():
	n = nn()

	ice= lm()

	ice.sort()
	out = []
	for i in range(n):
		if i%2==1:
			out.append(ice[i//2])

		else:
			out.append(ice[((i//2+n//2))])
	good= 0
	for i in range(n-1):
		if i%2==1:
			if out[i]<out[i+1] and out[i]<out[i-1]:
				good+=1
	print(good)
	print(*out)
solve()


import sys
readline = sys.stdin.readline

N = int(readline())
A = list(map(int, readline().split()))
A.sort()
Ans = [None]*N
A1 = A[:(N-1)//2][::-1]
A2 = A[(N-1)//2:]
for i in range((N-1)//2):
    Ans[2*i+1] = A1[i]
for i in range(N):
    if Ans[i] is None:
        Ans[i] = A2.pop()
ans = 0
for i in range(1, N-1):
    if Ans[i-1] > Ans[i] and Ans[i] < Ans[i+1]:
        ans += 1
print(ans)
print(*Ans)


n = int(input())
arr = sorted(list(map(int, input().split())), reverse=True)

t = n - (n - 1) // 2
ans = [0 for _ in range(n)]
for i in range(t):
    x = i * 2
    if x == n:
        x -= 1
    ans[x] = arr[i]

cur = 1
cur2 = n - 2
if n % 2 == 0:
    cur2 -= 1
for i in range(t, n):
    if ans[cur - 1] > arr[i] < ans[cur + 1]:
        ans[cur] = arr[i]
        cur += 2
    else:
        ans[cur2] = arr[i]
        cur2 -= 2

answer = sum(ans[i - 1] > ans[i] < ans[i + 1] for i in range(1, n - 1))
print(answer)
print(*ans)


#!/usr/bin/env python3
import sys
input = sys.stdin.readline

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

ans = [-1] * n
num = 0
if n % 2 == 1:
    for i in range(0,n,2):
        ans[i] = a.pop()
    for i in range(1,n,2):
        if ans[i-1] > a[-1] < ans[i+1]:
            num += 1
        ans[i] = a.pop()
    print(num)
    print(*ans)
else:
    for i in range(0,n,2):
        ans[i] = a.pop()
    ans[-1] = a.pop()
    for i in range(1,n-1,2):
        if ans[i-1] > a[-1] < ans[i+1]:
            num += 1
        ans[i] = a.pop()
    print(num)
    print(*ans)

n = int(input())
l = list(map(int,input().split()))
l.sort()
ans = []

if n%2 == 1:
    ans.append(l[n//2])
    for i in range(n//2):
        ans.append(l[i])
        ans.append(l[(n+1)//2 + i])
else:
    for i in range(n//2):
        ans.append(l[(n+1)//2 + i])
        ans.append(l[i])
num = 0
for i in range(1,n-1):
    if ans[i] < min(ans[i-1],ans[i+1]):
        num+=1
print(num)
print(' '.join(map(str,ans)))

from math import *
from random import *
from bisect import *
from math import *
n = int(input())
mas = sorted(list(map(int, input().split())))
otv = [0 for i in range(n)]
nxt = 0
for i in range(1, n, 2):
    otv[i] = mas[nxt]
    nxt += 1
for i in range(0, n, 2):
    otv[i] = mas[nxt]
    nxt += 1
res = 0
for i in range(1, n - 1):
    if otv[i] < otv[i + 1] and otv[i] < otv[i - 1]:
        res += 1
print(res)
print(' '.join(map(str, otv)))

from collections import Counter

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


n = int(input())
l = sorted(read_line())
def ok(ans):
    nums = l[:ans]
    rest = l[ans:]
    if len(rest) < ans + 1:
        return None
    rest = rest[-(ans + 1):]
    l2 = []
    for i in range(len(nums)):
        if nums[i] < rest[i] and nums[i] < rest[i+1]:
            l2.append(rest[i])
            l2.append(nums[i])
        else:
            return None
    l2.append(rest[-1])
    r = Counter(l)
    s = Counter(l2)
    for v in r:
        k = r[v] - s[v]
        l2 += [v] * k
    return l2

def _ok(ans):
    nums = l[:ans]
    rest = l[ans:]
    if len(rest) < ans + 1:
        return None
    rest = rest[-(ans + 1):]
    for i in range(len(nums)):
        if nums[i] < rest[i] and nums[i] < rest[i+1]:
            pass
        else:
            return None
    return 1


lo = 0
hi = n
while lo <= hi:
    mid = (lo + hi) // 2
    if _ok(mid) is not None:
        lo = mid + 1
    else:
        hi = mid - 1
a = ok(hi)
print(hi)
print(" ".join(map(str, a)))