Find an agent's worst-case spend under overlapping limits

Agent buildHard40 min

Your task

Finance keeps a list of spending rules for your agent, each over a stretch of days. Some cap what it may spend, and some come from contracts that commit it to a minimum. Before you approve the list, you want its worst case: the most the agent could spend in total while it obeys every rule.

Write most_spend(days, daily_cap, rules) that returns that total.

Input and output:

  • days: the number of days, 1 to 366, numbered 1 to days.
  • daily_cap: the most the agent can spend in one day, 1 to 1,000,000,000.
  • rules: up to 1,000 rules, each [first, last, low, high]. first and last are days, with first at or before last. low and high are from 0 to 1,000,000,000,000, with low at or below high.
  • Return an integer. Return -1 if no plan obeys every rule.

Rules:

  • A plan sets a spend for each day, a whole number from 0 to daily_cap.
  • A plan obeys a rule when its total spend from day first to day last, both included, is at least low and at most high.
  • Return the largest total over all the days, among the plans that obey every rule.

Examples

most_spend(days: int, daily_cap: int, rules: list[list[int]]) -> int
Example 1
Inputmost_spend(4, 10, [[1, 2, 0, 12], [2, 4, 5, 15]])
Output25
Example 2
Inputmost_spend(5, 100, [[1, 3, 0, 5], [2, 5, 0, 5]])
Output10
Example 3
Inputmost_spend(3, 5, [[1, 3, 0, 6], [1, 1, 4, 5], [3, 3, 4, 5]])
Output-1