Festival Intensity Deduction
Choose a contiguous interval maximizing sum minus squared maximum
A film festival is choosing a nonempty consecutive block of screenings for a special pass. Screening i contributes gains[i] units of projected net revenue and has an intensity rating of loads[i].
The festival must also provide audience support for the most intense screening in the chosen block. For a block from index l through index r, inclusive, its final value is
sum(gains[l..r]) - max(loads[l..r])².
Return [l, r] for a block with the greatest final value. If several blocks have the same value, choose the one with the smallest l; if there is still a tie, choose the one with the smallest r.
Indices are zero-based. Gains may be negative, and choosing an empty block is not allowed.
Examples
Example 1
Input: gains = [4,-7,8,3], loads = [1,4,2,2] Output: [2,3]
The last two screenings have combined gain 11 and maximum intensity 2. Their deduction is 4, and no other block has a greater final value.
Example 2
Input: gains = [2,2,-5,4], loads = [1,1,1,1] Output: [0,1]
The first two screenings and the final screening have equal final values. The block beginning at index 0 wins the tie.
Example 3
Input: gains = [-5,-2,-3], loads = [0,3,1] Output: [2,2]
Every possible block has a negative final value. The final screening alone is still the best nonempty choice.
Constraints
- 1 <= gains.length <= 100000
- loads.length == gains.length
- -1000000 <= gains[i] <= 1000000
- 0 <= loads[i] <= 1000000
An O(n)-time, O(n)-space solution is expected. Use integer arithmetic that can represent values beyond the 32-bit range. All intermediate values fit exactly in JavaScript's safe integer range.
Hints
Show hint 1Hint 1
Use a decreasing stack to build a Cartesian tree whose in-order traversal is the original index order and whose parent has at least its children's intensity.
Show hint 2Hint 2
For a node representing a maximum at index i, consider blocks inside its subtree that contain i. With gain prefix sums, their best value comes from a minimum prefix on the left and a maximum prefix on the right.
Follow-up questions
What an interviewer might ask once you have a working solution.
- Can the same approach handle a supplied penalty function of the maximum intensity instead of its square?
- How would you also count all optimal blocks without enumerating them?
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