Problem 495123 · hard · Phase 04 Non-Linear Data Structures

Best Rowing Crew

heaps · greedy · sorting · bounded heap

A club has n rowers; rower i has power[i] and stamina[i]. A crew is any non-empty group of at most k rowers, and its score is

(sum of the crew's power) * (minimum stamina in the crew)

Return the highest score any crew can achieve.

Examples

Input:  power = [3, 8, 4], stamina = [5, 2, 6], k = 2
Output: 35
Explanation: rowers 0 and 2 give (3 + 4) * min(5, 6) = 35. Adding rower 1 is not allowed
             (k = 2) and swapping them in drops the minimum stamina to 2.

Input:  power = [5, 2], stamina = [1, 10], k = 1
Output: 20

Constraints

  • 1 <= k <= n <= 10**5, 1 <= power[i], stamina[i] <= 10**5
  • Target complexity: O(n log n).

Goals

  • Fix one factor of a product by sorting, then optimise the other with a heap
  • Maintain the sum of the k largest values seen so far
  • Evaluate a candidate at every step, not only when the heap is full
Starting Python…