Problem 423585 · medium · Phase 04 Non-Linear Data Structures

Hiring From Both Ends of the Line

heaps · two heaps · greedy · simulation

Candidates stand in a line; costs[i] is the wage the i-th candidate asks for. You will hold exactly k hiring sessions. In each session you look at the first m candidates still in line and the last m candidates still in line (if fewer than 2m remain, you look at everyone), hire the one with the lowest wage, and remove them from the line. If the lowest wage appears in both groups, hire the one with the smaller index.

Return the total wage of the k hired candidates.

Examples

Input:  costs = [5, 3, 9, 1, 4, 6, 2], k = 2, m = 2
Output: 5
Explanation: session 1 looks at [5, 3] and [6, 2]; hires 2 (index 6). Session 2 looks at
             [5, 3] and [4, 6]; hires 3 (index 1). The candidate asking 1 is never looked at.

Input:  costs = [4, 4, 4], k = 3, m = 1
Output: 12

Constraints

  • 1 <= k <= len(costs) <= 10**5, 1 <= m <= 10**5, 1 <= costs[i] <= 10**5
  • Target complexity: O((m + k) log m).

Goals

  • Maintain two candidate windows that grow toward each other
  • Compare heap tops across two heaps with a defined tie rule
  • Refill windows carefully so no candidate is counted twice
Starting Python…