Select Up to Three Books from Distinct Genres
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Tests greedy optimization with category constraints, hash-map aggregation, and heap-based top-k selection.
You are building a reading recommendation system. Given a collection of books where each book belongs to a genre and has an associated score, you want to recommend up to three books to maximize the total score under one constraint: no two recommended books may share the same genre.
Write a function that accepts a list of books, where each book is represented as [genre, score], and returns the maximum total score achievable by selecting up to three books from different genres.
Rules:
- You may select 0, 1, 2, or 3 books.
- All selected books must have distinct genres.
- Only books with positive scores should be included in the selection (selecting a book with a non-positive score never improves the result).
Constraints
0 ≤ len(books) ≤ 10⁵genreis a string-1000 ≤ score ≤ 1000- Multiple books may belong to the same genre
Examples
Example 1
Input: select_top_books([['fiction', 10], ['mystery', 15], ['fiction', 30], ['poetry', 5], ['history', 12]])
Output: 57
Example 2
Input: select_top_books([['fiction', 9], ['fiction', 20], ['history', 4]])
Output: 24
Example 3
Input: select_top_books([])
Output: 0
Hints
Hint 1
Within each genre, only the highest-scoring book matters since you can pick at most one book per genre.
Hint 2
After finding the best score in each genre, select the top three positive values.
Hint 3
Use a heap or sorting to efficiently extract the largest scores from the per-genre maxima.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that within each genre, only the book with the highest score matters, since we can select at most one book per genre. This reduces the problem to two steps:
- Aggregate by genre: Build a dictionary mapping each genre to the maximum score among all books in that genre.
- Select the top three: Extract the three largest positive values from the per-genre maxima.
We use heapq.nlargest to efficiently find the top three scores without fully sorting all genres. We filter out non-positive scores because including them never improves the total.
Why It Works
Any valid selection uses at most one book per genre. If we've chosen a book from genre G, swapping it for the highest-scoring book in G keeps the genres distinct and cannot decrease the total. Therefore, some optimal solution uses only the per-genre maxima. Among those maxima (which already represent distinct genres), greedily picking the three largest positive values is optimal.
Complexity
- Time: O(n) to scan all books and build the genre map, plus O(g) to extract the top three from g genres using a heap. Total: O(n + g) where g ≤ n.
- Space: O(g) for the dictionary storing per-genre maxima.
Edge Cases
- Empty input returns 0.
- Fewer than three genres: select as many as available.
- All scores are non-positive: return 0 (select no books).
- Many books in one genre: only the highest-scoring one is considered.
from heapq import nlargest
from typing import List
def select_top_books(books: List[List]) -> int:
genre_best = {}
for genre, score in books:
if genre not in genre_best or score > genre_best[genre]:
genre_best[genre] = score
top_three = nlargest(3, (score for score in genre_best.values() if score > 0))
return sum(top_three)