KatInterview

Maximize Pay by Filling Gaps in a Shift Schedule

Greedy & IntervalsAuto-graded · 21 test cases
MediumAuto-gradedGreedy & Intervalsgreedydynamic-programmingarrays

Last updated

Tests greedy reasoning and run-based reformulation to optimally spend a limited number of schedule changes for maximum earnings with streak bonuses.

Maximize Pay by Filling Gaps in a Shift Schedule

You are managing a worker's schedule over n days. Each day is either already assigned as a shift day (1) or a rest day (0). The worker's pay follows two rules:

  • A worker earns wage dollars for every day they work.
  • A worker earns an additional bonus dollars on any worked day where the immediately preceding day was also worked (a consecutive bonus). The very first day is never eligible for this bonus since it has no prior day.

You are allowed to flip at most k rest days into shift days. Rest days are never mandatory to flip, and shift days cannot be removed.

Return the maximum total pay the worker can earn across all n days after making at most k such flips.

Input

  • n — total number of days in the schedule.
  • k — maximum number of rest days you may convert to shift days (0 <= k <= n).
  • wage — dollars earned per day worked.
  • bonus — extra dollars earned when two consecutive days are both worked.
  • schedule — a list of n integers, each 0 or 1, where 1 marks an original shift day and 0 marks an original rest day.

Output

A single integer representing the maximum total pay achievable.

Constraints

  • 1 <= n <= 100,000
  • 0 <= k <= n
  • 0 <= wage <= 10,000
  • 0 <= bonus <= 10,000
  • schedule[i] ∈ {0, 1}
  • The answer may exceed the 32-bit integer range; use 64-bit integers.

Examples

Example 1

Input: max_shift_pay(5, 2, 10, 5, [1, 0, 0, 1, 0])

Output: 55

Example 2

Input: max_shift_pay(4, 0, 7, 3, [1, 1, 0, 1])

Output: 24

Hints

Hint 1

Total pay can be expressed as (number of worked days) × wage + (number of adjacent worked-day pairs) × bonus. Focus on maximizing the number of adjacent pairs rather than thinking about each day in isolation.

Hint 2

The number of adjacent pairs equals (total worked days) minus (number of contiguous work blocks). So minimizing the number of separate work blocks is the real goal — and the only way to reduce blocks is to completely fill a gap of rest days between two blocks.

Hint 3

Since each fully filled gap saves exactly one block at a cost equal to the gap's length, you want to fill as many gaps as possible within your budget. Greedily pick the shortest gaps first. Any leftover conversions can simply extend an existing block without creating a new one.