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:

  1. Daily shift wage: Working on day i (0 <= i < n) pays pay[i]; resting on day i pays 0.
  2. Back-to-back streak reward: Every adjacent pair of days (i, i + 1) (0 <= i < n - 1) in which both day i and day i + 1 are worked pays an extra bonus (so a contiguous block of L worked days yields L - 1 bonuses).

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 days 0 and 2 for 8 + 8 = 16 (0 adjacent pairs).
  • Converting day 3 ("WOWW") earns 8 + 8 + 9 = 25 in wages plus 1 adjacent bonus on (2, 3) worth 7, totaling 32.
  • Converting day 1 ("WWWO") earns 8 + 3 + 8 = 19 in wages plus 2 adjacent bonuses on (0, 1) and (1, 2) worth 2 * 7 = 14, totaling 33.

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 0 and 3 ("WOOW") earns 16 + 18 = 34 in wages with 0 adjacent bonuses.
  • Every adjacent pair scores lower: (2, 3) ("OOWW") gives 6 + 18 + 5 = 29, (0, 1) ("WWOO") gives 16 + 4 + 5 = 25, and (1, 2) ("OWWO") gives 4 + 6 + 5 = 15.

Picking the two high-wage outer days yields 34.

Constraints

  • 1 <= n <= 1000, where n = len(schedule) = len(pay)
  • 0 <= k <= n
  • Every character of schedule belongs to {'W', 'O'}
  • 0 <= pay[i] <= 10^5
  • 0 <= bonus <= 10^5

Step-by-step walkthrough

  1. Understand the problem and rules

    We are given schedule (a string of 'W' workdays and 'O' days off over n days), a list pay of non-negative daily wages, a non-negative adjacency bonus, and a conversion budget k:

    • Every worked day i earns pay[i]; every day off earns 0.
    • Every adjacent pair (i, i + 1) where both day i and day i + 1 are worked earns one bonus. So a streak of 3 consecutive workdays (W W W) contains 2 adjacent pairs (0, 1) and (1, 2) and earns 2 * 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 * bonus
    

    With 1 <= n <= 1000 and 0 <= k <= n, our goal is to find the maximum total earnings.

  2. Why brute force and greedy both fail

    Trying every subset of up to k days off to convert requires checking up to C(1000, 500) combinations — an astronomical number with nearly 300 digits.

    A greedy shortcut such as "convert the k highest-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 earns 2 * bonus. We need a systematic way to weigh pay and streak bonuses together across the whole schedule.

  3. Key idea: track only `(conversions_used, yesterday_status)`

    Imagine walking through the schedule from day 0 to day n - 1. When you stand on day, how much of the past do you actually need to know to score day accurately?

    Only two small facts:

    1. used: how many 'O' -> 'W' conversions we have spent so far (0 <= used <= max_conversions, where max_conversions = min(k, schedule.count("O"))).
    2. Whether yesterday (day - 1) was off or worked: because bonus on day depends only on whether day - 1 was worked, not on day - 2 or 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 using used conversions when yesterday was off.
    • prev_work[used]: best total earnings so far using used conversions when yesterday was worked.

    Before day 0 starts, 0 conversions have been used, total earnings are 0, and there is no workday on day -1 to pair with. So we set prev_off[0] = 0 and fill all other slots with NEG_INF = float("-inf"). Because -inf + anything == -inf, impossible states stay -inf and never win a max(...) comparison.

  4. Derive the daily transitions

    On day (with character day_type = schedule[day] and wage today_pay = pay[day]), first ask: if we work today after used prior 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 + bonus today!

    So earn_if_work_today = max(prev_off[used], prev_work[used] + bonus) + today_pay. Now branch on day_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_off and curr_work arrays each day instead of modifying prev_off and prev_work in place? Because Option 2 writes to used + 1; if we mutated one array in place while looping used = 0, 1, ..., iteration used + 1 would immediately read the value we just wrote for today as if it came from yesterday, counting today twice!

  5. 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)
    
  6. Trace Example 1 day by day

    Let's trace schedule = "WOWO", pay = [8, 3, 8, 9], bonus = 7, k = 1 (max_conversions = 1). Below, -inf marks 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=32
    

    Notice what happens on Day 3 for used = 1: - prev_off[1] = 33 corresponds to converting day 1 ("WWWO", earning 19 in wages plus 2 * 7 = 14 in bonuses) and leaving day 3 off. - prev_work[1] = 32 corresponds to leaving day 1 off and converting day 3 ("WOWW", earning 25 in wages plus 1 * 7 = 7 in bonuses).

    Taking max(max(prev_off), max(prev_work)) picks 33.

  7. 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 most O(n * k)). Counting 'O's takes O(n) time, and then each of the n outer-loop days iterates over b + 1 budget counts, doing O(1) arithmetic and max comparisons per state (at most ~1,000,000 tiny iterations when n = k = 1000).
  • Space: O(b) (at most O(k)). At any moment we hold only four lists (prev_off, prev_work, curr_off, curr_work) of length b + 1, using float("-inf") as a sentinel value (a special marker for unreachable states that stays -inf when pay or bonus is added, so it can never beat a valid score).

Edge cases

  • Zero conversions allowed (k = 0): max_conversions = 0, so the arrays have length 1 (used = 0) and score the unchanged schedule in O(n) time.
  • Schedule is all 'W' ("WWW"): schedule.count("O") == 0, so max_conversions = 0 even if k is huge, returning total pay plus (n - 1) * bonus.
  • Budget exceeds days off (k > schedule.count('O')): Capping max_conversions avoids unreachable slots above schedule.count('O') and converts every 'O'.
  • Single-day schedule (n = 1): Because prev_work[0] starts at -inf, day 0 can never falsely claim an adjacency bonus.
  • pay[i] == 0 on a day off: Still considered for conversion, because bridging "WOW" with pay = [0, 0, 0] and bonus = 4 earns 8.
  • Maximum earnings (n = 1000, pay[i] = 10^5, bonus = 10^5): Reaches 1000 * 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' increments used; mandatory 'W' days transition from used to used.
  • Updating prev_off / prev_work in-place while looping used upward: Writing work[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] = 0 at the start: Pretends day -1 was a workday, awarding a phantom bonus if day 0 is worked.
  • Returning max(prev_off[k], prev_work[k]) instead of the maximum across all 0 <= used <= max_conversions: Fails whenever k is larger than the number of 'O' days (so used == k is unreachable), and ignores that the rule allows at most k conversions.

Alternative approaches

  • Full 3D DP table dp[day][used][worked]: Stores all n rows in O(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 in O(n * b) time and O(n * b) memory, though in Python n = 1000 requires raising sys.setrecursionlimit above 1000.

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 L pays L^2, knowing only whether yesterday was worked is no longer enough — extending a streak from 4 to 5 adds 5^2 - 4^2 = 9, whereas extending from 1 to 2 adds 2^2 - 1^2 = 3. We expand the DP state to dp[used][L] (the best earnings so far with used conversions and a current active work streak of length L ending yesterday) and apply telescoping (breaking a cumulative formula f(L) into daily marginal increments f(L) - f(L - 1) whose sum cancels out to f(L)): whenever a workday extends streak L - 1 to L, we add pay[day] + (L^2 - (L - 1)^2) = pay[day] + 2L - 1, and whenever an 'O' day stays off, L resets to 0. Because 0 <= L <= n and each (day, used, L) state transitions in O(1) time, this runs in O(n^2 * k) time and O(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 day depends only on day - 1's values (prev_off and prev_work), never on day - 2 or earlier. Allocating fresh curr_off and curr_work lists of size min(k, schedule.count('O')) + 1 on each day and replacing prev_off, prev_work = curr_off, curr_work drops extra memory from O(n * k) to O(k) while keeping O(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 >= 0 and bonus >= 0, we always convert c = min(k, schedule.count('O')) days off, fixing the total worked days at W = schedule.count('W') + c and daily pay at W * p. Notice that a streak of length L has L - 1 adjacent pairs, so summing across S separate work streaks gives (L_1 - 1) + ... + (L_S - 1) = W - S total bonuses — meaning maximizing bonuses is equivalent to minimizing the number of streaks S. Each run of 'O's sandwiched between two 'W' streaks is an interior gap: completely filling a gap of length g merges two streaks (S drops by 1) at cost g, whereas boundary 'O's or partial fills merely extend an existing streak (S changes by 0). So we greedily fill the shortest interior 'O' gaps first while budget remains — O(n log n) by sorting gap lengths, or O(n) using counting sort (bucketing integer gap lengths 1..n into a frequency array of size n + 1 instead 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

Similar questions

More Citadel interview questions

All 90 Citadel questions →