Sum of all Subarrays | Set 1 | Efficient Java program to compute sum of subarray elements ; function compute sum all sub - array ; computing sum of subarray using formula ; return all subarray sum ; Driver program to test above function
class GFG { public static long SubArraySum ( int arr [ ] , int n ) { long result = 0 ; for ( int i = 0 ; i < n ; i ++ ) result += ( arr [ i ] * ( i + 1 ) * ( n - i ) ) ; return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 } ; int n = arr . length ; System . out . println ( " Sum ▁ of ▁ SubArray ▁ " + SubArraySum ( arr , n ) ) ; } }