It’s like matter of Combinatorial optimization such as Knapsack problem or Bin packing problem.
In general, more detailed condition is necessary to write logic. For example, what if the combination does not result in 6 records? etc. (Case of 5 records, 3records, 2records and 2 records)