Optimal Shift Payout with Streak Bonuses
Medium · Coding & Algorithms · Software Engineer · HR Screen
Problem Statement
A worker's upcoming n-day calendar is given as a length-n string schedule where 'W' denotes a scheduled shift and 'O' denotes a scheduled rest day.
Payouts follow two rules:
- Daily shift wage: Working on day
i(0 <= i < n) payspay[i]; resting on dayipays0. - Back-to-back streak reward: Every adjacent pair of days
(i, i + 1)(0 <= i < n - 1) in which both dayiand dayi + 1are worked pays an extrabonus(so a contiguous block ofLworked days yieldsL - 1bonuses).
You may pick at most k rest days ('O') and convert them into worked shifts ('W'). Scheduled shifts ('W') are mandatory and can never be converted into rest days.
Implement:
def max_earnings(schedule: str, pay: list[int], bonus: int, k: int) -> int:
Return the largest total payout achievable after converting at most k rest days.
Examples
Example 1
max_earnings("WOWO", [8, 3, 8, 9], 7, 1)
# -> 33
Walk-through (k = 1 conversion available):
- Leaving
"WOWO"unchanged works days0and2for8 + 8 = 16(0adjacent pairs). - Converting day
3("WOWW") earns8 + 8 + 9 = 25in wages plus1adjacent bonus on(2, 3)worth7, totaling32. - Converting day
1("WWWO") earns8 + 3 + 8 = 19in wages plus2adjacent bonuses on(0, 1)and(1, 2)worth2 * 7 = 14, totaling33.
Bridging days 0 and 2 wins with 33.
Example 2
max_earnings("OOOO", [16, 4, 6, 18], 5, 2)
# -> 34
Walk-through (k = 2 conversions available):
- Converting days
0and3("WOOW") earns16 + 18 = 34in wages with0adjacent bonuses. - Every adjacent pair scores lower:
(2, 3)("OOWW") gives6 + 18 + 5 = 29,(0, 1)("WWOO") gives16 + 4 + 5 = 25, and(1, 2)("OWWO") gives4 + 6 + 5 = 15.
Picking the two high-wage outer days yields 34.
Constraints
1 <= n <= 1000, wheren = len(schedule) = len(pay)0 <= k <= n- Every character of
schedulebelongs to{'W', 'O'} 0 <= pay[i] <= 10^50 <= bonus <= 10^5
Step-by-step walkthrough
Understand the problem and rules
We are given
schedule(a string of'W'workdays and'O'days off overndays), a listpayof non-negative daily wages, a non-negative adjacencybonus, and a conversion budgetk:- Every worked day
iearnspay[i]; every day off earns0. - Every adjacent pair
(i, i + 1)where both dayiand dayi + 1are worked earns onebonus. So a streak of3consecutive workdays (W W W) contains2adjacent pairs(0, 1)and(1, 2)and earns2 * bonus. - We may convert at most
k'O'days into'W'days. Existing'W'days can never be turned into'O'days.
Schedule: W W W O Pay: 8 3 8 0 -> daily pay = 8 + 3 + 8 = 19 Pairs: └──┬──┴──┬──┘ -> pairs (0, 1) and (1, 2) earn 2 * bonusWith
1 <= n <= 1000and0 <= k <= n, our goal is to find the maximum total earnings.- Every worked day
Why brute force and greedy both fail
Trying every subset of up to
kdays off to convert requires checking up toC(1000, 500)combinations — an astronomical number with nearly300digits.A greedy shortcut such as "convert the
khighest-paid days off" also fails, because a day's true value depends on its neighbors:schedule = "W O O O O", pay = [0, 1, 1, 1, 5], bonus = 10, k = 1 Convert day 4 (highest pay): "W O O O W" -> pay 5 + 0 bonuses = 5 Convert day 1 (next to 'W'): "W W O O O" -> pay 1 + 1 bonus = 11 (wins!)Even harder, converting one
'O'inside"W O W"bridges two neighbors at once and earns2 * bonus. We need a systematic way to weigh pay and streak bonuses together across the whole schedule.Key idea: track only `(conversions_used, yesterday_status)`
Imagine walking through the schedule from day
0to dayn - 1. When you stand onday, how much of the past do you actually need to know to scoredayaccurately?Only two small facts:
used: how many'O' -> 'W'conversions we have spent so far (0 <= used <= max_conversions, wheremax_conversions = min(k, schedule.count("O"))).- Whether yesterday (
day - 1) was off or worked: becausebonusondaydepends only on whetherday - 1was worked, not onday - 2or earlier!
So after processing each prefix of days, we keep just two arrays of length
max_conversions + 1:prev_off[used]: best total earnings so far usingusedconversions when yesterday was off.prev_work[used]: best total earnings so far usingusedconversions when yesterday was worked.
Before day
0starts,0conversions have been used, total earnings are0, and there is no workday on day-1to pair with. So we setprev_off[0] = 0and fill all other slots withNEG_INF = float("-inf"). Because-inf + anything == -inf, impossible states stay-infand never win amax(...)comparison.Derive the daily transitions
On
day(with characterday_type = schedule[day]and wagetoday_pay = pay[day]), first ask: if we work today afterusedprior conversions, what is the best total we can achieve?- If yesterday was off, we had
prev_off[used]and get no bonus today. - If yesterday was worked, we had
prev_work[used]and earn+ bonustoday!
So
earn_if_work_today = max(prev_off[used], prev_work[used] + bonus) + today_pay. Now branch onday_type:If schedule[day] == 'W' (mandatory workday, 0 conversions spent): prev_off[used] ──┐ ├──► curr_work[used] = earn_if_work_today prev_work[used] ──┘ (curr_off[used] stays -inf: cannot skip 'W'!) If schedule[day] == 'O' (two choices): Option 1 (stay off, 0 conversions): curr_off[used] = max(prev_off[used], prev_work[used]) Option 2 (convert, +1 conversion): curr_work[used+1] = earn_if_work_today (if used < max_conversions)Why do we write into fresh
curr_offandcurr_workarrays each day instead of modifyingprev_offandprev_workin place? Because Option 2 writes toused + 1; if we mutated one array in place while loopingused = 0, 1, ..., iterationused + 1would immediately read the value we just wrote for today as if it came from yesterday, counting today twice!- If yesterday was off, we had
Write the rolling-array DP
# Sentinel for impossible DP states; adding pay or bonus to -inf stays -inf. NEG_INF = float("-inf") def max_earnings(schedule: str, pay: list[int], bonus: int, k: int) -> int: num_days = len(schedule) # Phase 1: Cap the conversion budget at the actual count of 'O' days, # since existing 'W' days never consume conversions. max_conversions = min(k, schedule.count("O")) # Phase 2: Rolling DP arrays indexed by `used` (0..max_conversions): # - prev_off[used]: best earnings so far with `used` conversions and yesterday OFF # - prev_work[used]: best earnings so far with `used` conversions and yesterday WORKED prev_off = [NEG_INF] * (max_conversions + 1) prev_work = [NEG_INF] * (max_conversions + 1) # Before day 0, 0 conversions have been used and there is no prior workday to pair with. prev_off[0] = 0 # Phase 3: Advance one day at a time, updating both status arrays. for day in range(num_days): curr_off = [NEG_INF] * (max_conversions + 1) curr_work = [NEG_INF] * (max_conversions + 1) day_type = schedule[day] today_pay = pay[day] for used in range(max_conversions + 1): # If we work today after `used` prior conversions, we earn today_pay, # plus `bonus` only when yesterday was ALSO worked (prev_work[used]). best_before_work = max(prev_off[used], prev_work[used] + bonus) earn_if_work_today = best_before_work + today_pay if day_type == "W": # Mandatory workday: cannot take the day off, costs 0 conversions. curr_work[used] = earn_if_work_today else: # Option 1: Leave 'O' as a day off (0 pay, 0 bonus, 0 conversions spent). curr_off[used] = max(prev_off[used], prev_work[used]) # Option 2: Spend 1 conversion (used -> used + 1) to turn 'O' into 'W'. if used < max_conversions: curr_work[used + 1] = earn_if_work_today prev_off = curr_off prev_work = curr_work # Phase 4: Because we may use AT MOST k conversions, take the maximum across all `used`. best_total = max(max(prev_off), max(prev_work)) return int(best_total)Trace Example 1 day by day
Let's trace
schedule = "WOWO",pay = [8, 3, 8, 9],bonus = 7,k = 1(max_conversions = 1). Below,-infmarks unreachable states:Stage prev_off[0] prev_off[1] prev_work[0] prev_work[1] notes ---------------- ----------- ----------- ------------ ------------ ----------------------------------------- Before day 0 0 -inf -inf -inf start with 0 used, no prior workday Day 0 ('W', 8) -inf -inf 8 -inf must work day 0 -> 0 + 8 = 8 Day 1 ('O', 3) 8 -inf -inf 18 stay off -> 8; convert -> 8 + 7 + 3 = 18 Day 2 ('W', 8) -inf -inf 16 33 work[0]=8+8=16; work[1]=18+7+8=33! Day 3 ('O', 9) 16 33 -inf 32 off[1]=33 (day 1 converted); work[1]=16+7+9=32Notice what happens on Day 3 for
used = 1: -prev_off[1] = 33corresponds to converting day 1 ("WWWO", earning19in wages plus2 * 7 = 14in bonuses) and leaving day 3 off. -prev_work[1] = 32corresponds to leaving day 1 off and converting day 3 ("WOWW", earning25in wages plus1 * 7 = 7in bonuses).Taking
max(max(prev_off), max(prev_work))picks33.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Sentinel for impossible DP states; adding pay or bonus to -inf stays -inf. NEG_INF = float("-inf") def max_earnings(schedule: str, pay: list[int], bonus: int, k: int) -> int: num_days = len(schedule) # Phase 1: Cap the conversion budget at the actual count of 'O' days, # since existing 'W' days never consume conversions. max_conversions = min(k, schedule.count("O")) # Phase 2: Rolling DP arrays indexed by `used` (0..max_conversions): # - prev_off[used]: best earnings so far with `used` conversions and yesterday OFF # - prev_work[used]: best earnings so far with `used` conversions and yesterday WORKED prev_off = [NEG_INF] * (max_conversions + 1) prev_work = [NEG_INF] * (max_conversions + 1) # Before day 0, 0 conversions have been used and there is no prior workday to pair with. prev_off[0] = 0 # Phase 3: Advance one day at a time, updating both status arrays. for day in range(num_days): curr_off = [NEG_INF] * (max_conversions + 1) curr_work = [NEG_INF] * (max_conversions + 1) day_type = schedule[day] today_pay = pay[day] for used in range(max_conversions + 1): # If we work today after `used` prior conversions, we earn today_pay, # plus `bonus` only when yesterday was ALSO worked (prev_work[used]). best_before_work = max(prev_off[used], prev_work[used] + bonus) earn_if_work_today = best_before_work + today_pay if day_type == "W": # Mandatory workday: cannot take the day off, costs 0 conversions. curr_work[used] = earn_if_work_today else: # Option 1: Leave 'O' as a day off (0 pay, 0 bonus, 0 conversions spent). curr_off[used] = max(prev_off[used], prev_work[used]) # Option 2: Spend 1 conversion (used -> used + 1) to turn 'O' into 'W'. if used < max_conversions: curr_work[used + 1] = earn_if_work_today prev_off = curr_off prev_work = curr_work # Phase 4: Because we may use AT MOST k conversions, take the maximum across all `used`. best_total = max(max(prev_off), max(prev_work)) return int(best_total)✅ Submit now — all tests should pass.
Intuition & how it works
Picture walking through the calendar one day at a time while holding k "overtime stickers" that can turn a day off ('O') into a workday ('W'). To calculate what today earns, you do not need to remember which specific earlier days received stickers — you only need to know how many stickers you have spent so far (used) and whether yesterday was worked (since only back-to-back workdays earn bonus). Solving a sequential problem by storing the best score for each compact summary of the past is dynamic programming (DP) (breaking a problem into stages and keeping only the optimal value for each distinct state), and keeping just yesterday's and today's state arrays instead of an n-row grid is a rolling-array optimization (discarding older DP rows as soon as no future step needs them).
Why do simpler strategies fail? Checking every subset of up to k days off explodes combinatorially (C(1000, 500) combinations). Meanwhile, greedily converting the highest-paying 'O' days misses adjacency bonuses: converting a zero-pay day off between two workdays ("WOW" -> "WWW") bridges two streaks and earns 2 * bonus, easily beating a higher-paid isolated day off.
Here is how the rolling arrays prev_off and prev_work evolve on Example 1 (schedule = "WOWO", pay = [8, 3, 8, 9], bonus = 7, k = 1):
Start: prev_off = [ 0, -inf], prev_work = [-inf, -inf]
Day 0 ('W', 8): prev_off = [-inf, -inf], prev_work = [ 8, -inf] (must work day 0)
Day 1 ('O', 3): prev_off = [ 8, -inf], prev_work = [-inf, 18] (convert: 8 + 7 + 3 = 18)
Day 2 ('W', 8): prev_off = [-inf, -inf], prev_work = [ 16, 33] (work[1]: 18 + 7 + 8 = 33!)
Day 3 ('O', 9): prev_off = [ 16, 33], prev_work = [-inf, 32] (work[1]: 16 + 7 + 9 = 32)
Result: max(16, 33, 32) = 33
Complexity
Let n = len(schedule) and b = min(k, schedule.count('O')) be the effective conversion budget.
- Time:
O(n * b)(at mostO(n * k)). Counting'O's takesO(n)time, and then each of thenouter-loop days iterates overb + 1budget counts, doingO(1)arithmetic andmaxcomparisons per state (at most ~1,000,000tiny iterations whenn = k = 1000). - Space:
O(b)(at mostO(k)). At any moment we hold only four lists (prev_off,prev_work,curr_off,curr_work) of lengthb + 1, usingfloat("-inf")as a sentinel value (a special marker for unreachable states that stays-infwhenpayorbonusis added, so it can never beat a valid score).
Edge cases
- Zero conversions allowed (
k = 0):max_conversions = 0, so the arrays have length1(used = 0) and score the unchanged schedule inO(n)time. - Schedule is all
'W'("WWW"):schedule.count("O") == 0, somax_conversions = 0even ifkis huge, returning total pay plus(n - 1) * bonus. - Budget exceeds days off (
k > schedule.count('O')): Cappingmax_conversionsavoids unreachable slots aboveschedule.count('O')and converts every'O'. - Single-day schedule (
n = 1): Becauseprev_work[0]starts at-inf, day0can never falsely claim an adjacency bonus. pay[i] == 0on a day off: Still considered for conversion, because bridging"WOW"withpay = [0, 0, 0]andbonus = 4earns8.- Maximum earnings (
n = 1000,pay[i] = 10^5,bonus = 10^5): Reaches1000 * 10^5 + 999 * 10^5 = 199,900,000, well within standard integer bounds.
Common mistakes
- Charging a conversion on existing
'W'days: Only turning'O'into'W'incrementsused; mandatory'W'days transition fromusedtoused. - Updating
prev_off/prev_workin-place while loopingusedupward: Writingwork[used + 1]in-place causes the very next loop step (used + 1) to read today's newly written value as if it were yesterday's, spending multiple conversions and earning multiple paychecks on the same day. - Initializing
prev_work[0] = 0at the start: Pretends day-1was a workday, awarding a phantombonusif day0is worked. - Returning
max(prev_off[k], prev_work[k])instead of the maximum across all0 <= used <= max_conversions: Fails wheneverkis larger than the number of'O'days (soused == kis unreachable), and ignores that the rule allows at mostkconversions.
Alternative approaches
- Full 3D DP table
dp[day][used][worked]: Stores allnrows inO(n * b)memory. Useful if a follow-up asks you to reconstruct which exact'O'days were converted by walking backward from the winning final state. - Top-down memoized recursion
dfs(day, rem_k, prev_worked): Mirrors Hint 2 directly inO(n * b)time andO(n * b)memory, though in Pythonn = 1000requires raisingsys.setrecursionlimitabove1000.
Follow-up questions
- What changes if a contiguous run of L worked days pays a non-linear streak reward such as L^2 instead of (L - 1) * bonus? When a streak of length
LpaysL^2, knowing only whether yesterday was worked is no longer enough — extending a streak from4to5adds5^2 - 4^2 = 9, whereas extending from1to2adds2^2 - 1^2 = 3. We expand the DP state todp[used][L](the best earnings so far withusedconversions and a current active work streak of lengthLending yesterday) and apply telescoping (breaking a cumulative formulaf(L)into daily marginal incrementsf(L) - f(L - 1)whose sum cancels out tof(L)): whenever a workday extends streakL - 1toL, we addpay[day] + (L^2 - (L - 1)^2) = pay[day] + 2L - 1, and whenever an'O'day stays off,Lresets to0. Because0 <= L <= nand each(day, used, L)state transitions inO(1)time, this runs inO(n^2 * k)time andO(n * k)rolling space. - How do you reduce the DP memory footprint from O(n * k) down to O(k)? Notice that every transition on
daydepends only onday - 1's values (prev_offandprev_work), never onday - 2or earlier. Allocating freshcurr_offandcurr_worklists of sizemin(k, schedule.count('O')) + 1on each day and replacingprev_off, prev_work = curr_off, curr_workdrops extra memory fromO(n * k)toO(k)while keepingO(n * k)time; the only trade-off is that reconstructing the exact converted indices requires keeping parent pointers or the full table. - When every day offers the exact same base wage, how can you solve the problem greedily in O(n log n) or O(n) time? When every worked day pays
p >= 0andbonus >= 0, we always convertc = min(k, schedule.count('O'))days off, fixing the total worked days atW = schedule.count('W') + cand daily pay atW * p. Notice that a streak of lengthLhasL - 1adjacent pairs, so summing acrossSseparate work streaks gives(L_1 - 1) + ... + (L_S - 1) = W - Stotal bonuses — meaning maximizing bonuses is equivalent to minimizing the number of streaksS. Each run of'O's sandwiched between two'W'streaks is an interior gap: completely filling a gap of lengthgmerges two streaks (Sdrops by1) at costg, whereas boundary'O's or partial fills merely extend an existing streak (Schanges by0). So we greedily fill the shortest interior'O'gaps first while budget remains —O(n log n)by sorting gap lengths, orO(n)using counting sort (bucketing integer gap lengths1..ninto a frequency array of sizen + 1instead of comparison-sorting them):
```python def max_earnings_equal_pay(schedule: str, daily_pay: int, bonus: int, k: int) -> int: n = len(schedule) budget = min(k, schedule.count("O")) total_worked = schedule.count("W") + budget if total_worked == 0: return 0
gap_counts = [0] * (n + 1)
streaks = 0
i = 0
while i < n:
j = i
while j < n and schedule[j] == schedule[i]:
j += 1
if schedule[i] == "W":
streaks += 1
elif i > 0 and j < n:
gap_counts[j - i] += 1
i = j
if streaks == 0:
streaks = 1 # zero initial 'W's: place all `budget` conversions in 1 block
else:
for gap_len in range(1, n + 1):
while gap_counts[gap_len] > 0 and budget >= gap_len:
budget -= gap_len
gap_counts[gap_len] -= 1
streaks -= 1
return total_worked * daily_pay + (total_worked - streaks) * bonus
```
Follow-up questions
- What changes if a contiguous run of L worked days pays a non-linear streak reward such as L^2 instead of (L - 1) * bonus?
- How do you reduce the DP memory footprint from O(n * k) down to O(k)?
- When every day offers the exact same base wage, how can you solve the problem greedily in O(n log n) or O(n) time?
Similar questions
- Exchange and National Best Quote Aggregator
- Sliding Square Submatrix Sums
- Largest Group Around an Anchor Interval
- Largest Forward Gain in a Sequence
- Lazy-Expiring Session Token Store
- Dynamic Weighted Random Sampler with Updates
More Citadel interview questions
- Minimum Edits for Palindromic Fixed-Size Blocks Medium
- Multi-Venue Order Book for BBO and NBBO Medium
- Regional Temperature Regressions and Greedy Predictor Selection for NYC Medium Pro
- One-Shot Batch Selection for Labeling 200 of One Million Feature Vectors Medium Pro
- Binary Classification over Variable-Size Point Clouds with Missing Entries Hard Pro
- Exchange and National Best Quote Aggregator Medium Pro
- Sliding Square Submatrix Sums Medium Pro
- Largest Group Around an Anchor Interval Medium Pro
- Navigating a High-Stakes Engineering Obstacle Medium Pro
- Real-Time Telemetry Ingestion and Sub-2s Alerting Engine Medium Pro