You can use meet-in-the-middle to reduce the time $ O (n ^ { lceil k / 2 rceil}) $.

To simplify, I guess $ k $ is same.

The idea is as follows:

- Partition $ A $ in two parts.
- For each part, calculate a sorted list of sums of $ k / $ 2 parts of the room.
- For each $ k / $ 2-sum in the first part, use binary search to find the best $ k / $ 2-sum in the second part conforms to the constraints.

As noted, the idea poses several problems:

- It assumes that the optimal solution contains exactly $ k / $ 2 comes out of each game.
- It works in time $ O (n ^ {k / 2} log n) $.
- He uses $ O (n ^ {k / 2}) $ Memory.

To manage the first difficulty, there are several options. We could just repeat the whole algorithm $ sqrt {k} $ time. Alternatively, there could be deterministic means to achieve the same goal. Here is a hybrid solution:

- Randomly partition $ A $ in $ k ^ 3 $ rooms $ P_1, ldots, P_ {k ^ 3} $ (something much bigger $ k ^ 2 $ would work). With a high probability, each element of the optimal solution is in its own part.
- Consider all possible partitions of $ A $ in two parts of the form $ P_1, ldots, P_i $ and $ P_ {i + 1}, ldots, P_ {k ^ 3} $. One of them will contain exactly $ k / $ 2 elements of the optimal solution.

To manage the second difficulty, we must be slightly more careful in the implementation. Using fusion (the familiar mergesort routine), it should be possible to calculate $ k / $ 2– sums of each part $ O (n ^ {k / 2}) $. The last step can be implemented by $ O (n ^ {k / 2}) $ using a classic technique with two pointers (the first pointer goes up on the first half, the second goes down on the second half).

There are tricks to reduce the memory required from $ O (n ^ {k / 2}) $ at $ O (n ^ {k / 4}) $: further divide each part into two sub-parts. You can easily review all $ k / $ 2– are in the first part considering all the pairs of $ k / $ 4– are in its subparts. Binary search on the second part can then be implemented using the two-point technique.