Given an array , find the sum of the differences between the maximum and minimum elements over all subarrays. A subarray is a continguous part of an array.
Constraints: and
Think of an alien invasion with alien spaceships approaching Earth. The array represents the distances (in light-years) of each spaceship from Earth, while the array contains their respective speeds in light-years per minute. We have a cannon that starts fully charged. After shooting down a spaceship, it takes one whole minute to recharge before it can fire again. How many spaceships can be destroyed before Earth is invaded?
Example: and . Answer will be since we can destroy the first ship in the zeroeth second, the second ship in the first before the third one invades us in the second second.
Possible Solutions
arrival_times and observe that we can greedily destroy the oncoming spaceships at times . Count the number of elements satisfying arrival_times[i] > i: once an element does not satisfy it, break and return the count so far.