Input: arr[] = {1, 2, 3}
Output: 20
Explanation: Possible Subarrays are: {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}.
Products of all the above subarrays are 1, 2, 3, 2, 6 and 6 respectively.
Sum of all products = 1 + 2 + 3 + 2 + 6 + 6 = 20.
Input: arr[] = {1, 2, 3, 4}
Output: 84
Explanation:
Possible Subarrays are: {1}, {2}, {3}, {4}, {1, 2}, {2, 3}, {3, 4}, {1, 2, 3}, {2, 3, 4}, {1, 2, 3, 4}. Products of all the above subarrays are 1, 2, 3, 4, 2, 6, 12, 6, 24 and 24.
Sum of all products = 1 + 2 + 3 + 4 + 2 + 6 + 12 + 6 + 24 + 24 = 84.
a + b + c + d+ ab + bc + cd + abc + bcd + abcd
= (a + ab + abc + abcd) + (b + bc + bcd) + (c + cd) + d
= a * (1+ b + bc + bcd) + (b + bc + bcd) + (c + cd) + d
Now, the value of underlined expression (b + bc + bcd) can be calculated once and use twice.
Again, (b+ bc + bcd) + (c + cd) = b * (1 + c + cd) + (c + cd)
In the same way, the expression (c + cd) can be used twice.
The latter part is the same as above.