# Win a War (or at least a few battles)

You have an army of size $n$ that you need to split up to fight $k$ battles simultaneously against an opposing army $A$. In each battle, the army with the most troops present wins - no one wins a tie. Your scouts have just reported back with the enemy troops' movements - how can you divide your army to win the most battles? What's more, if 2 different arrangements win the same number of battles, you prefer the arrangement that beats the most enemy soldiers.

# Input

The integers $n, k$ and an array $A$ that contains the number of enemy troops at each battle location.

# Output

An array corresponding to A that represents the number of your own troops you will send to that location. There are most likely be multiple solutions - you may return any possible solution that maximizes the amount of battles won while also maximizing the numbers of soldiers beaten within the maximum amount of battles won.

# Example

$n = 100, k = 5, A = [20, 20, 20, 20, 20]$

The enemy has split their army evenly - to win the maximum amount of battles, 4, we can simply ignore battle 1 and distribute evenly among the other 4, for example $[0, 25, 25, 25, 25]$.

$n = 50, k = 5, A = [40, 30, 20, 10, 0]$

We're outnumbered, but we can still win 3 battles. $[0, 0, 25, 15, 10]$ would win 3 battles, but remember, we want to win against larger enemy forces if possible, so a correct optimal answer could be $[0, 35, 0, 14, 1]$

# More Input/Output Examples

Only one of many possible outputs is shown.

```
n, k, A -> Output
1, 1, [0] -> [1]
2, 2, [1,1] -> [2, 0]
10, 3, [4, 3, 3] -> [5, 0, 5]
100, 3, [50, 25, 25] -> [60, 40, 0]
100, 5, [33, 34, 33, 0, 0] -> [0, 50, 40, 5, 5]
```

This is code golf, so shortest solution in each language wins.

## 1 answer

# JavaScript, 227 bytes

```
(n,k,A,C=(a,b)=>a?[...C(--a,b),b(a)]:[],f=m=>m?C(n+1,i=>f(m-1).map(([p,s])=>
[[...p,i],s+i])).flat():[[[],0]])=>f(k).map(([b,s])=>a=s-n?a:b.map((a,b)=>(q
=A[b])<a&&(e++,f+=q),e=f=0,[,c,d]=a)&&e<c|e==c&f<d?a:[b,e,f],a=[,-1])&&a[0]
```

Explanation: recursively generates all possible troop arrangements of length $k$ whose sum is $n$ and picks the one with the maximum score.

Try it online! (229 bytes, because TIO uses an old version of Node.js that has a parsing issue when an arrow function appears inside a call)

## 2 comments

Will there ever be an input where no battle can be won? For example

`10, 3, [50, 60, 70]`

? — DJMcMayhem 13 days ago@DJMcMayhem hm, I didn't think of it, so I'm going to say no now — Quintec 13 days ago