Problem statement:
问题陈述:
Find sum of all subarray sums out of an array.
查找数组中所有子数组总和的和。
Example:
例:
Input array:
[1, 2, 3, 4]
Output:
50
Solution:
解:
Of course, there exists an easy solution where we can use three for loops with time complexity (O (n3)). The outer loop and intermediate loop are to iterate through all subarrays and the innermost one is to compute the sum. But here, we are not going to discuss this simple brute-force solution. Rather we will discuss an efficient way to minimize the time complexity.
当然,存在一个简单的解决方案,其中我们可以使用三个具有时间复杂度(O(n3))的 for循环。 外循环和中间循环将遍历所有子数组,而最内层将计算总和。 但是在这里,我们将不讨论这种简单的暴力解决方案。 相反,我们将讨论一种最小化时间复杂度的有效方法。
Let's look at an example first,
我们先来看一个例子
Array = [1, 2, 3, 4]
Sub-arrays are
[1] =1
[2] =2
[3] =3
[4] =4
[1, 2] =1+2=3
[2, 3] =2+3= 5
[3, 4] =3+4 =7
[1, 2, 3] = 1+2+3= 6
[2, 3, 4] = 2+3+4= 9
[1, 2, 3, 4] = 1+2+3+4 = 10
Total sum= 50