[Question]
  [
Given an n non-negative integers, how many numbers must be changed so that each number x appears x times? You cannot add or remove elements, only replace them with other numbers.
For example:
```
1 6 23 6 9 23 1 1 6
```
can be turned into:
```
1 6 2 6 6 2 6 6 6
```
with 5 changes, which is optimal.
## Test cases
```
0 => 1
1 2 3 => 1
5 5 5 5 5 => 0
23 7 4 8 => 3
100 100 100 6 => 4
5 5 5 5 5 5 => 1
1 2 2 4 4 4 4 9 9 9 9 => 5
```
Shortest code wins!
  
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 16 bytes
```
L:…æ·∫ãŒ©·µõC‚Çå}∆õ?√û·πÖL}g
```
Simple bruteforce, probably can be golfed more.
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCJMOsm+4bqLzqnhtZtD4oKMfcabP8Oe4bmFTH1nIiwiIiwiWzIzLDcsNCw4XSIsIjMuNC4xIl0=)
```
L:…æ·∫ãŒ©·µõC‚Çå}∆õ?√û·πÖL}g¬≠‚Å°‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å°‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å£‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å§‚Å™‚Äè‚Äè‚Äã‚Å°‚Å†‚Å°‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å°‚Å™‚Äè‚Å†‚Å™‚Å™‚Å†‚Å™‚Å™‚Å†‚Å™‚Å™‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å£‚Å°‚Å™‚Äè‚Äè‚Äã‚Å°‚Å†‚Å°‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å¢‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å£‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å§‚Å™‚Äè‚Äè‚Äã‚Å°‚Å†‚Å°‚Äå‚Å§‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å£‚Å¢‚Å™‚Äè‚Å†‚Å™‚Å™‚Å†‚Å™‚Å™‚Å†‚Å™‚Å™‚Å†‚Å™‚Å™‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å§‚Å£‚Å™‚Äè‚Äè‚Äã‚Å°‚Å†‚Å°‚Äå‚Å¢‚Å°‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å£‚Å£‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å£‚Å§‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å§‚Å°‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å§‚Å¢‚Å™‚Äè‚Äè‚Äã‚Å°‚Å†‚Å°‚Äå‚Å¢‚Å¢‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å§‚Å§‚Å™‚Äè‚Äè‚Äã‚Å°‚Å†‚Å°‚Äå¬≠
L:…æ·∫ã              # ‚Äé‚Å°Nth cartesian power of range [1, length]
    Œ©   }         # ‚Äé‚Å¢Filter by items where
     ·µõC‚Çå          # ‚Äé‚Å£Count of each item is item
         ∆õ    }   # ‚Äé‚Å§Map through list
          ?√û·πÖL    # ‚Äé‚Å¢‚Å°Length of multiset difference between input and item
               g  # ‚Äé‚Å¢‚Å¢Push minimum
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [R](https://www.r-project.org), 88 bytes
```
\(x,n=sum(x|1))min(combn(rep(1:n,n),n,\(r)`if`(all(names(t<-table(r))==t),sum(r!=x),n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY5LCsJADIb3niLiJoEUOm3VIo7ncNFFH7RQ6IzSTqELT-AV3FTBQ3kb-xgpwk9C8iV_8njW_auQ79YUTvg5R9ixlk2rsLsJIlVqzC4q1VjnVxQHzZpYc4Q1xWURY1JVqBOVN2iOjknSKh8ISWmIR496Lbthnois_73ADF2iDcgTiNVYCQaPwf_rbRkWWeJOxPMZ9gwBQ2j7_uziugxL2FkYTDCYFqx-h-aP-n7OXw)
[Answer]
# Haskell + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 28 bytes
```
mMl<df**<fb(jn rl)<<dpS uq<l
```
I didn't want to brute force this, so I didn't. Although brute forcing would probably be shorter.
## Explanation
First we find all the strictly descending integer partitions of the length of the input. We convert these to "perfect lists". This gives us all the perfect lists with the same size as the input. Then we take use the set difference to remove the elements in the input from each perfect list, these represent the number of replacements that need to be done. Then we get the size of the smallest element and output that.
## Reflection
This answer feels *painfully* long. There are a couple things here:
* `dpS uq` is a bad way to get strictly descending integer partitions. It is 6 bytes long and slower than it needs to be. There should be a 3-byte version.
* This isn't the first time I've wanted a function that zips and then concatenates, but I apparently haven't added it. It would be useful here.
* There should be a shorter way to replicate every item in a list its own number of times (currently `fb(jn rl)`). I remember noticing that some obscure combination of functions did this, but I can't remember which. It's really bothering me.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
J·πóLƒã‚±Æ`∆ë∆án‚Å∏¬ß·πÇ
```
A monadic Link that accepts a list of integers and yields the minimal number to alter to form a *perfect array*.
**[Try it online!](https://tio.run/##y0rNyan8/9/r4c7pPke6H21cl3Bs4rH2vEeNOw4tf7iz6f///9FGOgpAZKmjYAxGIG4sAA "Jelly ‚Äì Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/r4c7pPke6H21cl3Bs4rH2vEeNOw4tf7iz6f/RSQ93ztA53J71qGGOgq2dwqOGuZqR//9HRxvE6nApRBvqKBjpKBiD2aY6CggEFjEy1lEw11Ew0VGwgKg2MNBRQBBmmNogOmMB "Jelly ‚Äì Try It Online").
### How?
Constructs all lists of the same length as the input using an alphabet of `1` through to that length (with the elements in all possible orders). Filters these down to *perfect arrays*. Counts the differing entries of each with respect to the input (by summing the results of a vectorised not-equal). Returns the minimum.
```
J·πóLƒã‚±Æ`∆ë∆án‚Å∏¬ß·πÇ - Link: list of integers, Array
J            - indices {Array} -> [1..length(Array)]
  L          - length {Array}
 ·πó           - {Indices} Cartesian power {Length}
                 -> all arrays of length length(Array) formed from 1..length(Array)
       ∆á     - keep those for which:
      ∆ë      -   is invariant under?:
    ‚±Æ`       -     map across itself with:
   ƒã         -       count occurrences
        n‚Å∏   - {that} not-equal? (vectorises) {Array}
          ¬ß  - sums
           ·πÇ - minimum
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 29 bytes
```
{&/+/~x=+{+/x=\:x}/'+!#/2##x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pW09fWr6uw1a7W1q+wjbGqqNVX11ZU1jdSVq6o5eJKc9AxABKGCkYKxkDaVAEKgWwjYwUTBXMFC5C0gYECDJshKwMAUYQUvg==)
`+!#/2##x` Generate all n-tuples with values in [0,n), where n is the length of the input.  
`{...}/'` For each tuple, run until convergence:  
`+/x=\:x` ... Replace each value with its count.1  
`~x=+` element-wise comparison between the input and each generated tuple.  
`&/+/` Find the minimum number of different values.
1 If this converges it must have reached a perfect array. Right now I can't think of a proof that it always converges (or equivalently, there are no cycles of length >1).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ƒÅ¬§√£ í√ê¬¢Q}‚Ç¨-ƒÄO√ü
```
Port of [*@mathScat*'s Vyxal answer](https://codegolf.stackexchange.com/a/269105/52210).
[Try it online](https://tio.run/##ASwA0/9vc2FiaWX//8SBwqTDo8qSw5DColF94oKsLcSAT8Of//9bNSw1LDEsMiwyXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PNB5acnjxqUmHJxxaFFh7buuhdbq1Rxr8D8//r/M/OtogVifaUMdIxxhIm@pAIZBtZKxjrmOiYwGSNjDQgWEzZGVghcY6xjqGcFEjHSMo2xDMjgUA).
**Explanation:**
```
ƒÅ          # Push a list in the range [1, (implicit) inpu-length]
 ¬§         # Push its last item (without popping): the length
  √£        # Cartesian power, to create all possible lists of this length
    í       # Filter it by:
    √ê      #  Triplicate the current list
     ¬¢     #  Pop two, and count how many times each item occurs
      Q    #  Check that this list of counts and current list are still the same
   }‚Ç¨      # After the filter: map over each remaining list:
     -     #  Subtract the values at the same positions from the (implicit) input-list
      ƒÄ    # Check for each difference that it's NOT 0 (0 if 0; 1 otherwise)
       O   # Sum the checks of each inner list together
        √ü  # Pop and push the minimum
           # (which is output implicitly as result)
```
[Answer]
# Python3, 742 bytes
Rather long, but non-brute force solution (for the sake of variety)
```
from itertools import*
D=lambda d,n,K,U:{**{a:b for a in d if(b:=[j for j in d[a]if j not in K])},n:[*K,*U]}
def P(n,d,r,F):
 U=d.get(n,[])
 d={i:d[i]for i in d if i!=n}
 k=[[],[]]
 for i in d:
  if i<n or len(d[i])!=i:k[i>F]+=d[i]
 if len(k[1])>=r:yield D(d,n,K:=k[1][:r],U),K;return
 for K in combinations(k[0]+k[1],r):
  if[]==k[1]or any(j in K for j in k[1]):yield D(d,n,K,U),K
def f(a):
 d,I={},0
 for i in a:d[i]=d.get(i,[])+[I];I+=1
 q=[(len(a),len(a),d,0)]
 M=-1
 while q:
  n,A,d,C=q.pop(0)
  if all(i==len(d[i])for i in d):M=min(M,C)if M!=-1 else C;continue
  if n==0:continue;
  if len(L:=d.get(n,[]))!=n:
   r,F=n-len(L),A-n
   for u,i in P(n,d,r,F):
    if M==-1 or C+len(i)<M:q+=[(F,A-n,u,C+len(i))]
  q+=[(n-1,A,d,C)]
 return M
```
[Try it online!](https://tio.run/##lVLRbtowFH3PV1yeahODktIxZupKFRVSlUXaC0@WH0KTrC6JE0LQhBDfznwdGO00qUwWSjj33HPuPU69a18rM5rUzfGYN1UJus2atqqKDeiyrpq27z2JIimXaQIpMyxiC77v9/cJX0JeNZCANpCCzsmSC/nmsDeHyUTp3L6bqsX/kaIHZrjsR6y/UAcvzXL4QQxLWcPmlHuwEOnwZ9ZaSCrqQSr2mqdSK1TUZxfQPWEOHqyElMoSlQeXuhVxlHsDFisyQ7Cf9oTmK6kf5soXCHhIwupKhoo@iIbvdFak8ETcglwgLnmj2IKyaNpk7bYxnU@EPi9VudQmaXVlNlYjUD42sIZ2/lIJp4DhmB1xYUSXXJzpR0fn4wLJSYIqKXsW@wML3i2XuCxOEWmMyJfPavrsi9CDtZAEF0ooOz1SFlC7aCwGtvzrVRcZrHE8wx5tbSbWw7qqSUC7xJKiIFqIP4ldIqU8FqU2JGYzaolxzwpCVmwymE1fKtNqs806DSNEwM/QtMNQ8Dt/f6/2MgzOAfbShRk4AmWPA4MY2m6ZM/7wZYATiwV6W8rMxzZN72O@9u3mc@xnW3bGcXFwFTMIu30R6u4R4mPdaNOSnMh@mdTEvjO4CW6Gm7rQLbHdlHr/ooRwC6PPaV/gdD6n3o7gK9zB5ArvIIDzb/wfM1wzRQhjsJOM4Rs@QnuudJjYc2dPCKO/gjn@Bg) (includes extra/longer test cases)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
Ôº©‚åäÔº•Œ¶Ôº•Ôº∏¬≤Ôº¨Œ∏‚åïÔº°‚Æå‚çò‚äóŒπ¬≤1‚ÅºŒ£ŒπÔº¨Œ∏Œ£Ôº•Œπ‚åà‚ü¶‚Å∞‚ÅªŒª‚ÑñŒ∏Œª
```
[Try it online!](https://tio.run/##RU5BCoMwEPxK8LSBFKoFofTU2nqqIPUoHlINGlhjNYnt79OohS4LM8sOM1N3fKoHjs7lk1QGEq4NZFLJ3vaQ8RekEo2YVpoPb88iRu5CtaaDkVJGUqmaMyI8xCwmLeDCtSiM92rhOtgnigakl0WLNgiDBW6j5aih8AnL6@/mj@IXKxnJ@GdtUe49l8pqQEaSwfqWIyNIaUW3OTlXliEjsY85rHDcWLhuXFVuN@MX "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation:
```
Ôº•Ôº∏¬≤Ôº¨Œ∏‚åïÔº°‚Æå‚çò‚äóŒπ¬≤1
```
Generate all subsets of `{1..l}`, where `l` is the length of the input array.
```
Œ¶....‚ÅºŒ£ŒπÔº¨Œ∏
```
Filter for those that sum to `l`.
```
Ôº©‚åäÔº•...Œ£Ôº•Œπ‚åà‚ü¶‚Å∞‚ÅªŒª‚ÑñŒ∏Œª
```
Calculate the number of changes required for each subset and output the minimum.
[Answer]
# JavaScript (ES7), 122 bytes
Brute force.
```
a=>eval("for(m=s=a.length,n=s**s;n--;)a.map(c=(x,i)=>(c[v=n/s**i%s+1|0]=-~c[v],d+=v!=x,v),d=0).some(v=>c[v]-v)|d>m?m:m=d")
```
[Try it online!](https://tio.run/##fc7fa8IwEAfw9/0VN0FI9NKm1v1Aue4PkT6EJnUdTSJGgg/iv15TkMm6sXDcw92H@@ZLRRWaY3c4Cee1GVoaFFUmqp7NWn9klgKprDduf/pER2GxCFsnxJarzKoDa4idseNUsWYXyeVp383DsrjImsQ1zWrUS4rPdMbIUZPkWfDWsEjVuBSRX3RlP@zGkp7xofEu@N5kvd@zlu1kzTlMXp5D8TRxBcIKofyh/3IvCI@66@Tk1K1KhDeENcL7983kyl@5UiI82uuIk1v/m3uPHv833AA "JavaScript (Node.js) ‚Äì Try It Online")
### Commented
This is a version without `eval()` for readability.
```
a => {                  // a[] = input array
  for(                  // main loop:
    m =                 //   m = minimum score
    s = a.length,       //   s = size of a[]
    n = s ** s;         //   n = counter, initialized to s ** s
    n--;                //   decrement n down to 0
  )                     //
    a.map(c =           // c = object to count value occurrences
    (x, i) =>           // for each element x at index i in a[]:
      ( c[              //   increment c[v]
          v =           //   where v is:
            n / s ** i  //     a value in [1 .. s] computed
            % s + 1 | 0 //     according to n and i
        ] = -~c[v],     //
        d += v != x,    //   increment d if v != x
        v               //   yield v
      ),                //
      d = 0             //   start with d = 0
    )                   // end of map()
    .some(v =>          // for each value v in the result of map():
      c[v] - v          //   trigger some() if c[v] != v
    ) |                 // end of some()
    d > m ?             // if some() was triggered or d > m:
      m                 //   do nothing
    :                   // else:
      m = d;            //   update m to d
  return m              // return m
}                       //
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 39 37 bytes
```
{‚åä/+/¬®‚çµ‚àò‚â†¬®{‚çµ/‚ç®{‚äÉ‚àß‚åø{‚ç∫=‚ç¥‚çµ}‚å∏‚çµ}¬®‚çµ},‚ç≥‚ç¥‚ç®‚ç¥‚çµ}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lFPl762/qEVj3q3PuqY8ahzwaEV1UC2/qNeIN3V/Khj@aOe/UCRXbaPercAJWof9ewAUWAdtTqPejeDxVdAZf@7PWqbQF1DN0PVcD3qmwo03E3BUMFIwRjOM4VBuIiRsYKJgrmCBUKDgQEcm2FqVDD9DwA "APL (Dyalog Classic) ‚Äì Try It Online")
```
{‚åä/+/¬®‚çµ‚àò‚â†¬®{‚çµ/‚ç®{‚äÉ‚àß‚åø{‚ç∫=‚ç¥‚çµ}‚å∏‚çµ}¬®‚çµ},‚ç≥‚ç¥‚ç®‚ç¥‚çµ}
{                               ,‚ç≥‚ç¥‚ç®‚ç¥‚çµ} generate all n-length arrays of numbers 1-n (where n is the input length)
          {‚çµ/‚ç®              ¬®‚çµ}        keep only arrays for which
              {‚äÉ‚àß‚åø{‚ç∫=‚ç¥‚çµ}‚å∏‚çµ}           all numbers appear a number of times equal to their value (perfect arrays)
      ‚çµ‚àò‚â†¬®                              for each, find the number of elements that differ from the input
 ‚åä/+/¬®                                  and return the minimum
```
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), ~~119~~ 88 bytes
Saved 31 bytes thanks to @ZaMoC
---
88 bytes version. [Try it online!](https://tio.run/##fYzLCsIwFET3fsWFQtESsA9fKIUILtwIarsLUS71UgNNkCYuROyv141Q60IYBuYMHI3uShqdKrBtNcfzMt0pI7DZotbKlBtlHZqCGs8f84wqKpw4oilJmDSvRXRCKZv8fqvINoatzYXzDDUdOOc5VtWDe76U7TDIyToo0JINRoN9rYwTWjzDl5SrbkYMYgZJH04ZdOlfccJgzmDCYPEjCkNg8N2zP9KPt30D)
```
m@a_:=Min[a~HammingDistance~#&/@Select[Range[n=Tr[1^a]]~Tuples~n,And@@SameQ@@@Tally@#&]]
```
119 bytes version. [Try it online!](https://tio.run/##fYxBawJBDIXv/opAQaoEuq7WlpaFKfTQQ4ViFzyEIGGJuwMzoTjjoYi/fRUpWHsohIT38t4XJXcaJftG@n7jZP1UvYRQb3dKtYTw7QRviErmqjrdCfOQB/EcW/nc0d6qd7U2d04OuPBGbxKjt/bVpyzWKJ3qPLxznxq0yVTvvoImWoq16gyNccPM/e241pShkaRpPBp8bL1lirQvDszPFzlBKBGm1@Y9wmWuX@UU4QFhhvD4B1QUgPB7z/@B/nD7Iw)
```
f@a_:=AllTrue[Tally@a,#[[2]]==#[[1]]&]
m@a_:=With[{n=Length@a},Min[HammingDistance[a,#]&/@Select[Tuples[Range@n,n],f]]]
```
Ungolfed version. [Try it online!](https://tio.run/##lZBdS8MwFIbv@ysOCENHwK7zC6XgmBcKDob2LgQJ8dgW0nQk6YVs@@319APXXQwrhCQned8n70khfYaF9LmSdf3i1mi/UPmFtfKbS2s/BNzHEAAstE5shTyRWrc3gsEZ55EQEMfNbka73W5wFsJEPASr3CwzaVJ0SXkSvio/K418ayCGVzSpz/oXNmgL1y6/RipVC1yWlfFuzxpAJyR3Um00Ov7WCLghgqEM3f2BQLp31FTynn/cd@cYPkKGZ1kUuUmfcuelUdjkow8QMIHLx2N666a2@ZAgCBqcTxN0HpR06KYXwdrmxvOTH7QN943rL9WMQcRgPkp7zeAwRjmiOYNbBlcM7salCUNgMJxv/p@sD1fXPw)
```
IsPerfectArray[arr_] := 
  AllTrue[Tally[arr], #[[2]] == #[[1]] || #[[2]] == 0 &];
MinChangesToPerfectArray[arr_] := 
  Module[{n = Length[arr], perms, perfectArrays, changeCounts}, 
   perms = Tuples[Range[n], n];
   perfectArrays = Select[perms, IsPerfectArray];
   changeCounts = HammingDistance[arr, #] & /@ perfectArrays;
   Min[changeCounts]];
(*Test cases*)
Print[MinChangesToPerfectArray[{0}]];
Print[MinChangesToPerfectArray[{1, 2, 3}]];
Print[MinChangesToPerfectArray[{5, 5, 5, 5, 5}]];
Print[MinChangesToPerfectArray[{23, 7, 4, 8}]];
Print[MinChangesToPerfectArray[{100 , 100 , 100 , 6}]];
Print[MinChangesToPerfectArray[{5, 5, 5, 5, 5, 5}]];
```
[Answer]
# [Python 3](https://www.python.org/) - 157 Bytes
This is a brute force solution. It won't always run fast, but it gets the job done nicely.
```
lambda l:(N:=len(l))-max([sum([l[p]==k[p]for p in range(N)])for k in[[i//(N**j)%N+1for j in range(N)]for i in range(N**N)]if all([g==k.count(g)for g in k])])
```
[Try it online!](https://tio.run/##XY1ZDoIwEIav0heTKVbZXAhJr9ALNH2oS7FQSoOQ6OmxFUzUTGb78s8/7jncOpsXrp8mRY1sTxeJTAmspOZqwWC8aeUD@H1sgRvuBKWNr6rrkUPaol7a6goMCxxQ4xHnOo6BRVGNV2ydBlz/KAPRXySKPNQKSWOAV95/e@5GO0D1tqyCshH@weR67TFXwBOBiW8pyUg@j3uyxLxmOTmSHSkWXZKQTx7@9OHCe78A)
**Explanation**
```
(lambda l:                            #Define a function that takes a list l
    (N:=len(l))-                      #Return N (the length of l) minus the following
    max([                             #The maximum value in this list
        sum([                         #Sum the True values in this list
            l[p]==k[p]                #p-th item in the input equals item in k
            for p in range(N)         #Where p is the p-th item in the lists
        ])
        for k in                      #Loop through the items in this list; k equals the item
        [
            [
                i//(N**j)%N+1         #Goes through all possible arrays with max N and length N
                for j in range(N)     #j is equal to 1,2...N
            ]
            for i in range(N**N)      #Do this for i = 1,2...N**N to get all possible lists
        ]
        if all([                      #Only include the list if all of these Booleans are true
            g==k.count(g)             #Is g equal to how many times g occurs?
            for g in k                #Do this for every item in all possible lists
        ])
    ])
)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 112 bytes
```
f=(z,a=[],i=0)=>1/z[i]?Math.min(...z.map((_,j)=>(++j!=z[i])+f(z,t=[...a],i+1,t[j]=-~t[j]))):a.some((v,i)=>v-i)*i
```
[Try it online!](https://tio.run/##fc5LboMwEAbgfU8x3Y3LYMwjD0VycoKewEKVlUJiBDgKiAWLXJ0OUlRUWtUa2Qt/v39XdrDd@e5ufdj6z2IqNQ@OZLXJyWkl9DGORuPy07vtr7JxLUopR9nYG@IHVXyPQVC96tmIoORorw0Ty/Egpt5UuQ4f8yGEOFjZ@aZAHMhxcgideHPT2bedrwtZ@wuWaBRLWK0ogvhl5WKChCD9of9yG4JlnpqdWrskJdgRZAT77zfZpb96lSJYtu2M2WX/9j6r5/9NXw "JavaScript (Node.js) ‚Äì Try It Online")
Recursive is bit shorter
[Answer]
# [Python](https://www.python.org), 111 bytes
```
f=lambda L,l=0,p=0,s=0:(d:=len(L)-p)and min(f(L,k,p+k,s+max(0,k-L.count(k)))for k in[*range(-~l,-~d//2),d])or s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU1LboMwEN1zitllhgyJA6FNkZwTsO-i6sItobUwtgVEaje5SDds2jvlNjWCqNXTSPM-M-_rx38O786O4_d5qJPD1dXSqPalUlCykYJ9mF6KAqtCmpPFkhJPylbQaos1ltywXzfcr1v1gYKbpNy8urMdsCGi2nXQgLZPcafs2wmTi-HkUm23KXH1TMHtl9rHKWpCFJwPLYKKCDQ7kGA2vTd6wJU8riiCeFZb5VHbgTHWi0_sKPi-CzJqrlFPyvx-vLYC5BF20Q5SyOY1hxsCFVGawT3s4TCxLNoJAbe5m6T9v3z-9ysNJzMeFgQrn1t_AQ)
### obsolete [Python](https://www.python.org), 128 bytes
```
f=lambda L,*s:[r:=len(L)-sum(s)]and min([f(L,*s,k)for k in range([0,*s][-1]+1,-~r//2)]+[sum(max(0,t-L.count(t))for t in[*s,r])])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU5BboMwELzzir1lTUxiILQpEnkB9x4sH9wmtFbARsZI7aXqP3rh0v4pv6ldiFKNVtqd2Zndr5_-3b0aPU3fo2uS_eWzqVrZPR0l1DQeSm7Lqj1prEkyjB0OREh9hE5p5A2GDXomjbFwBqXBSv1yQs48LXiSinVKkw-73WZErHmwd_INGXVJvXk2o3boyJ_ZeTP3UVYQQZY_HoPQhlTT-_uMlBEoaqCCdjP0rXK4qg4rEkE8s53sUWlHMVaLTqghXu-tp1HRBlVg5vjp0jGoDpBGKWSQz20BV_iRRVkO97CDfZjyKGUMrnUXqN2__eKWlXnLjIcFXirmq78)
## How?
* Creates all strictly increasing partitions of the length of the input.
* For each partition:
	+ Counts how many instances of each element are in the list and
	+ if there are too few adds the number missing to the tally for that partition
* Takes the minimum over all sums.
[Answer]
# [Desmos](https://desmos.com/calculator), 123 bytes
```
f(l)=[sgn([B[B=j].count-jforj=B]^2.max)L+sgn(B-l)^2.totalfori=[0...L^L]].min
L=l.length
B=l[mod(floor(Li/L^{[1...L]}),L)+1]
```
Brute force. This theoretically works for any list, but in practice it errors out for input lists with greater than 5 elements because of Desmos's 10000 element restriction.
[Try It On Desmos!](https://www.desmos.com/calculator/cmggrtolhp)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/mpfni46tib)
]