Solar Credit Rate Window

Maximum rounded-down ratio over duration-bounded subarrays

HardBinary SearchMonotonic QueuePrefix Sums

A solar farm records consecutive operating periods. Period i lasts duration[i] minutes and contributes energy[i] units of net energy. Net energy can be negative when the farm consumes more energy than it produces.

An auditor must select a nonempty contiguous block of complete periods whose total duration is between min_duration and max_duration, inclusive. Periods cannot be split.

The block's credited rate is

floor(total net energy / total duration).

Here, floor rounds toward negative infinity. For instance, a ratio of -1.5 has credited rate -2.

Return the largest credited rate among all eligible blocks. The input guarantees that at least one eligible block exists.

Examples

Example 1

Input: energy = [3,9,7,-4], duration = [2,3,2,1], min_duration = 4, max_duration = 5
Output: 3

The middle two periods have total energy 16 and total duration 5, so their credited rate is 3. No eligible block has a higher credited rate.

Example 2

Input: energy = [-3,-4], duration = [2,2], min_duration = 3, max_duration = 4
Output: -2

Only the block containing both periods has an eligible duration. Its total energy is -7 over 4 minutes, which rounds down to -2.

Example 3

Input: energy = [5,12,4], duration = [4,2,3], min_duration = 2, max_duration = 5
Output: 6

The single middle period has energy 12 and duration 2, giving a credited rate of 6. It is eligible and is better than every other eligible block.

Constraints

  • 1 <= len(energy) == len(duration) <= 100000
  • -1000000 <= energy[i] <= 1000000
  • 1 <= duration[i] <= 10000
  • 1 <= min_duration <= max_duration <= 1000000000
  • At least one nonempty contiguous block has total duration in [min_duration, max_duration]

Use integer arithmetic for feasibility checks. Under these constraints, all intermediate integers are exactly representable by JavaScript Number. The intended complexity is O(n log R) time and O(n) auxiliary space, where R is the range of possible integer rates.

Hints

Show hint 1

For an integer candidate rate r, a block qualifies exactly when sum(energy[i] - r * duration[i]) is nonnegative. Is feasibility monotone in r?

Show hint 2

For each ending prefix, eligible starting prefixes lie in a moving interval determined by cumulative duration. Maintain the smallest transformed prefix value in that interval.

Follow-up questions

What an interviewer might ask once you have a working solution.

  • How would you also return one block attaining the optimal credited rate?
  • How would the feasibility test change if blocks also had to contain between a given minimum and maximum number of periods?

Practice this with an AI interviewer

Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.

Start this problem