Python coding

Most pay without back-to-back shifts

You're offered one shift a day, and the shift on day i pays pay[i]. You never work two days in a row: taking day i rules out days i - 1 and i + 1. Return the largest total you can earn.

pay may be empty and its values are non-negative. Aim for one pass and O(1) extra space.

Besides the tests, one large input (31 days) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • max_pay([2,7,9,3,1]) → 12
  • max_pay([5,1,1,5]) → 10
  • max_pay([2,3,2]) → 4
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Let best[i] be the most you can earn from days 0 to i. Either you skip day i, or you work it and day i − 1 stays off.

Hint 2

best[i] = max(best[i - 1], best[i - 2] + pay[i]). Each step reads only the last two totals, so two variables replace the list.

Hint 3

Working every other day is not enough: on [5, 1, 1, 5] both alternations earn 6, while days 0 and 3 earn 10.

Solution and why it works
pythonO(n) · O(1)
def max_pay(pay: list[int]) -> int:
    before, best = 0, 0                  # best totals up to two days ago and up to yesterday
    for p in pay:
        before, best = best, max(best, before + p)   # skip today, or work it after a day off
    return best

The best plan up to day i either skips day i, leaving the best plan up to day i − 1, or works it: day i − 1 is off and the rest is the best plan up to day i − 2. Two smaller answers per day: O(n) time with two running values, where plain recursion re-solves them about 1.6ⁿ times. Greedy fails: alternating days earns 6 on [5, 1, 1, 5], and grabbing the biggest pay first earns 3 on [2, 3, 2]; the answers are 10 and 4.

Related lab: Big-O growth