KatInterview

Select Up to Three Books from Distinct Genres

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchgreedyhashmapheap

Last 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⁵
  • genre is 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.