Ctrl K

Showcase: Profit Plus Variety

Hard
A shop is putting together a display. You are given a list goods, where goods[i] = [profit, category] is an item's profit and its category. Exactly count items must go on display (each item from the list can be used at most once). The value of a display is the total profit of the chosen items plus the **square** of the number of distinct categories among them. Return the largest possible value of a display.
Example 1
goods=[[7, 1], [6, 1], [2, 2]], count=2 → 14

The two category-1 items give 7 + 6 + 1² = 14; items [7, 1] and [2, 2] give 7 + 2 + 2² = 13. So 14 is the best.

Example 2
goods=[[10, 3], [9, 3], [1, 1], [1, 2]], count=3 → 24

Taking [10, 3], [9, 3] and [1, 1] gives profit 20 with two categories: 20 + 2² = 24, while three distinct categories reach only 10 + 1 + 1 + 3² = 21.

Example 3
goods=[[5, 1]], count=1 → 6
Constraints
  • 1 ≤ len(goods) = n ≤ 10⁵
  • goods[i] = [profit, category]
  • 1 ≤ profit ≤ 10⁹
  • 1 ≤ category ≤ n
  • 1 ≤ count ≤ n
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNarrowest Range Touching Every List HardJobs With a Cooldown MediumSpread Out the Labels MediumCross Out Half the List MediumClearing the Stacks Evenly Easy
loading Python…
Input
goods=[[7, 1], [6, 1], [2, 2]], count=2
Expected
14

Run checks the first 3 tests in your browser. Submit checks all 108 tests on the server, hidden ones included.