KatInterview

Daily Flat-Fee Cap on Overlapping Job Charges

Greedy & IntervalsAuto-graded · 19 test cases
MediumAuto-gradedGreedy & Intervalsline-sweepintervalsdifference-array

Last updated

Sum per-day min(active cost, flat fee) over huge day ranges using an event sweep, with the result taken modulo 1,000,000,007.

A batch system runs n jobs. Job i is active on every calendar day from first_day[i] to last_day[i], both inclusive. On each day it is active, it adds unit_costs[i] to that day's bill.

For every day, the operator independently picks one of two ways to pay:

  • Regular billing: pay the sum of unit_costs[i] over all jobs active that day.
  • Flat fee: pay exactly flat_fee for that day, regardless of which jobs are active.

The choice on one day does not affect any other day. A day with no active jobs costs 0 under regular billing.

Return the smallest possible total bill over all days, modulo 1_000_000_007.

Details

  • Compare the true (unreduced) daily sum against flat_fee. Apply the modulus only to the final accumulated total.
  • If there are no jobs, the answer is 0.
  • Day numbers may be very large, so the solution must not depend on iterating over every day in the range.

Constraints

  • 0 <= n <= 10^5, and unit_costs, first_day, last_day all have length n.
  • 0 <= unit_costs[i] <= 10^9
  • 1 <= first_day[i] <= last_day[i] <= 10^9
  • 0 <= flat_fee <= 10^9
  • Return an integer in [0, 1_000_000_006].

Examples

Example 1

Input: min_total_billing([10, 20], [1, 2], [3, 4], 15)

Output: 55

Example 2

Input: min_total_billing([5], [10], [10], 3)

Output: 3

Example 3

Input: min_total_billing([4, 7, 2], [1, 2, 5], [5, 6, 8], 10)

Output: 57

Hints

Hint 1

The days do not interact: the cheapest total is the sum over days of the cheaper option for that single day.

Hint 2

Each job adds a constant to a contiguous block of days. Record +cost at the first day and -cost at last_day + 1, then sweep the sorted event days.

Hint 3

Between two consecutive event days the active sum is constant, so that stretch contributes (number of days) * min(active sum, flat_fee). Do not reduce the active sum modulo anything before the min.