You have a store credit of credit dollars and a list of books, where each book is a [price, weight] pair. Find a combination of at least two books whose prices sum to exactly credit and whose total weight is as small as possible.
Return that combination as a list of [price, weight] pairs. If no valid combination exists, return an empty list. Each book may be used at most once.
Function Signature
def lightest_book_combination(credit: int, books: list[list[int]]) -> list[list[int]]:
Rules
-
books[i]
is
[price, weight]
. Two books with the same price and weight are still two separate books, and each can be used once.
-
A valid combination has at least two books, and its prices add up to exactly
credit
.
-
Return the chosen books sorted ascending by price, then by weight.
-
If several valid combinations share the minimum total weight, return the one whose sorted list is lexicographically smallest: compare the first pairs, then the second pairs, and so on, comparing each pair by price and then by weight.
-
If no valid combination exists, return
[]
.
Constraints
-
1 <= credit <= 1000
-
2 <= len(books) <= 20
-
1 <= price <= 1000
-
1 <= weight <= 1000
Examples
Input: credit = 10, books = [[3,5],[7,4],[5,2],[5,3],[2,1]]
Output: [[5,2],[5,3]]
The combinations that reach exactly 10 are prices 5 + 5 (weight 2 + 3 = 5), 3 + 7 (weight 5 + 4 = 9), and 2 + 3 + 5 (weight 1 + 5 + 2 = 8 with the [5,2] book, or 9 with the [5,3] book). The lightest is the pair of books priced 5, with total weight 5.
Input: credit = 6, books = [[2,5],[4,3],[1,1],[5,9]]
Output: [[2,5],[4,3]]
Prices 2 + 4 sum to 6 with weight 5 + 3 = 8, and prices 1 + 5 sum to 6 with weight 1 + 9 = 10. No other combination reaches 6, so the answer has weight 8.
Input: credit = 10, books = [[10,1],[3,2],[7,2],[5,2],[5,2]]
Output: [[3,2],[7,2]]
The single book [10,1] matches the credit on its own but does not count, because a combination needs at least two books. Prices 3 + 7 and 5 + 5 both reach 10 with weight 4. The sorted list [[3,2],[7,2]] comes before [[5,2],[5,2]] because its first price, 3, is smaller.