Subarray Sum
Given a array of integers, find out the sum of all subarrays
Ex:[1,2,3] -> [1], [2], [3], [1,2], [2,3], [1,2,3]
sum = 20
Every element arr[i] appears in two types of subsets:
In sybarrays beginning with arr[i]. There are
(n-i) such subsets. For example [2] appears
in [2] and [2, 3].
In (n-i)*i subarrays where this element is not
first element. For example [2] appears in
[1, 2] and [1, 2, 3].
Sum = (n-i) + (n-i)*i = (n-i)(i+1)
public static long SubArraySum( int arr[] , int n )
{
long result = 0;
// computing sum of subarray using formula
for (int i=0; i<n; i++)
result += (arr[i] * (i+1) * (n-i));
return result ;
}Duplicted number increase by 1
E.g. [1,2,2,3,3] -> [1,2,3,4,5]
Last updated
Was this helpful?