Maximize Pay by Filling Gaps in a Shift Schedule
Greedy & IntervalsAuto-graded · 21 test casesLast 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
wagedollars for every day they work. - A worker earns an additional
bonusdollars 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 ofnintegers, each0or1, where1marks an original shift day and0marks an original rest day.
Output
A single integer representing the maximum total pay achievable.
Constraints
1 <= n <= 100,0000 <= k <= n0 <= wage <= 10,0000 <= bonus <= 10,000schedule[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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reformulating the pay function
Instead of simulating the schedule day by day, rewrite the total pay in terms of two counters:
W— total days workedP— number of adjacent worked-day pairs (consecutive pairs)
total pay = W × wage + P × bonus
A consecutive pair (i-1, i) exists exactly when both days are worked. If the worked days form R contiguous blocks (runs), then a run of length L contributes L - 1 pairs internally. Summing across all runs:
P = W - R
total pay = W × wage + (W - R) × bonus
So the goal is to maximize W and minimize R.
Step 1 — use every available conversion
Since wage >= 0 and bonus >= 0, converting a rest day to a shift day never decreases pay. Each conversion adds at least wage to the total. So the number of conversions is fixed at c = min(k, zeros), and W = original_ones + c is determined before any further decisions.
Step 2 — minimize blocks by filling internal gaps
The only way to reduce R is to completely fill a gap — a contiguous stretch of rest days sitting between two existing shift blocks. Filling a gap of size g costs g conversions and saves exactly one block (merging two blocks into one). Gaps at the start or end of the schedule cannot merge anything.
Since every merge has equal value (saves one block) and costs the gap's size, this is a straightforward unit-value knapsack: pick as many gaps as possible within budget c by always choosing the smallest gap first. This is justified by a standard exchange argument — swapping a larger chosen gap for a smaller unchosen one keeps the count the same at equal or lower cost.
Any leftover conversions after full merges extend an existing block and never open a new one, so R is unaffected.
Special case — no original shift days
With no existing block to attach to, all c conversions must form a fresh contiguous block to maximize pairs. That yields max(0, c - 1) adjacent pairs.
Why this is correct
- All conversions are used — argued above using non-negativity of
wageandbonus. - Greedy smallest-gap-first is optimal — equal-value items, minimize cost per item, standard exchange argument.
- Gaps are independent — filling one gap does not change any other gap's size, so the greedy selection is straightforward.
- Partial fills don't help — a partially filled gap still leaves two separate blocks. Only a complete fill counts.
Complexity
- Time:
O(n log n)— a single pass to collect gap sizes (O(n)) plus sorting them (O(n log n)). The sort dominates; a counting sort over sizes bounded bynwould reduce this toO(n)if needed. - Space:
O(n)— for the list of shift positions and the gap list.
Edge cases
| Scenario | Behavior |
|---|---|
k = 0 | c = 0; answer is the unmodified schedule's value |
| All zeros | No anchor block; use max(0, c - 1) pairs |
| No zeros | c = 0; single run of length n; P = n - 1 |
k > number of zeros | Clamped by min(k, zeros) |
| Gap larger than remaining budget | Greedy loop stops; no later (larger) gap can fit either |
wage = 0 or bonus = 0 | Formula still holds; "not worse" rather than strictly better |
Reference solution
from typing import List
def max_shift_pay(n: int, k: int, wage: int, bonus: int, schedule: List[int]) -> int:
# Use every available conversion — adding a shift day never hurts when wage, bonus >= 0.
conversions = min(k, n - sum(schedule))
workdays = sum(schedule) + conversions
shift_positions = [i for i, v in enumerate(schedule) if v == 1]
# Special case: no original shift days exist.
# Place all conversions as one contiguous block to maximize consecutive pairs.
if not shift_positions:
adjacent_pairs = max(0, conversions - 1)
return workdays * wage + adjacent_pairs * bonus
# Identify contiguous blocks of original shift days and collect internal gap sizes.
# An "internal gap" is a run of zeros strictly between two shift-day blocks.
runs = 1
internal_gaps = []
for left, right in zip(shift_positions, shift_positions[1:]):
gap = right - left - 1
if gap == 0:
continue # these two positions belong to the same block
runs += 1
internal_gaps.append(gap)
# Greedily fill the smallest internal gaps first.
# Each fully filled gap merges two blocks into one, reducing run count by 1.
internal_gaps.sort()
used = 0
merged = 0
for gap in internal_gaps:
if used + gap > conversions:
break
used += gap
merged += 1
# Adjacent pairs = total worked days minus remaining number of blocks.
adjacent_pairs = workdays - (runs - merged)
return workdays * wage + adjacent_pairs * bonus