DSCPPAS271 - Editorial

Problem Statement:

Given an array arr[] consisting of N integers, the task is to find the sum of the differences between the maximum and minimum elements of all possible subarrays from the given array.

Approach:

The key insight in solving this problem is to efficiently calculate how many times each element in the array acts as a minimum or maximum in the subarrays that include it. By doing so, we can compute the sum of the differences between the maximum and minimum elements across all subarrays.

Step-by-Step Explanation:

Step 1: Understand Contribution of Each Element

For each element in the array:

  • Determine how many subarrays it is the maximum element.
  • Determine how many subarrays it is the minimum element.

The contribution of an element as a maximum is positive, while its contribution as a minimum is negative. Therefore, for each element, the net contribution to the sum of differences is:

Net Contribution = Number of subarrays where it is max - Number of subarrays where it is min x * element value

Step 2: Utilize Monotonic Stacks

To efficiently calculate the number of subarrays in which each element is the maximum or minimum:

  • Use a monotonic increasing stack to find how many subarrays an element is the minimum.
  • Use a monotonic decreasing stack to find how many subarrays an element is the maximum.

Monotonic Increasing Stack:

  • Helps in finding how many subarrays have the current element as the minimum by counting subarrays extending to the left and right.

Monotonic Decreasing Stack:

  • Helps in finding how many subarrays have the current element as the maximum by similarly counting subarrays extending to the left and right.

Step 3: Calculate the Sum Using Contributions

Once the counts are obtained for each element:

  • Calculate the net contribution for each element using the derived formula.
  • Accumulate these contributions to get the final result.

Time Complexity:

  • Time Complexity: The algorithm runs in O(N) time since each element is processed using stacks.
  • Space Complexity: The space complexity is O(N) for storing the stacks and additional arrays for left and right boundaries.