Input: arr[] = [1, 4, 5, 3, 2]
Output: 116
Explanation: Sum of all possible subarrays of the array [1, 4, 5, 3, 2] is 116.
Input: arr[] = [1, 2, 3, 4]
Output: 50
Explanation: Sum of all possible subarrays of the array [1, 2, 3, 4] is 50.
Let's take an example: arr[] = [1, 4, 5, 3, 2]
All subarrays : [1], [1, 4], [1, 4, 5], [1, 4, 5, 3], [1, 4, 5, 3, 2], [4], [4, 5], [4, 5, 3], [4, 5, 3, 2], [5], [5, 3], [5, 3, 2], [3], [3, 2], [2]
Third element arr[2] appears 3 time when subarray start with arr[0]: [1, 4, 5], [1, 4, 5, 3], [1, 4, 5, 3, 2]
Third element arr[2] appears 3 time when subarray start with arr[1]: [4, 5], [4, 5, 3], [4, 5, 3, 2]
Third element arr[2] appears 3 time when subarray start with arr[2]: [5], [5, 3], [5, 3, 2]
So, We can clearly see that, For any element arr[i] in an array of size n, it appears in exactly (i + 1) * (n - i) subarrays.
For arr[] = [1, 2, 3], sum of subarrays is: arr[0] * ( 0 + 1 ) * ( 3 - 0 ) + arr[1] * ( 1 + 1 ) * ( 3 - 1 ) + arr[2] * ( 2 + 1 ) * ( 3 - 2 ) = 1*3*3 + 2*2*2 + 3*3*1 = 20