zoukankan      html  css  js  c++  java
  • Sum of all Subarrays | Set 1

    Given an integer array ‘arr[]’ of size n, find sum of all sub-arrays of given array.

    Examples:

    Input   : arr[] = {1, 2, 3}
    Output  : 20
    Explanation : {1} + {2} + {3} + {2 + 3} + 
                  {1 + 2} + {1 + 2 + 3} = 20
    
    Input  : arr[] = {1, 2, 3, 4}
    Output : 50

    // Simple Java program to compute sum of
    // subarray elements
    class GFG {
         
        // Computes sum all sub-array
        public static long SubArraySum(int arr[], int n)
        {
            long result = 0;
          
            // Pick starting point
            for (int i = 0; i < n; i ++)
            {
                // Pick ending point
                for (int j = i; j < n; j ++)
                {
                    // sum subarray between current
                    // starting and ending points
                    for (int k = i; k <= j; k++)
                        result += arr[k] ;
                }
            }
            return result ;
        }
    

      If we take a close look then we observe a pattern. Let take an example

    arr[] = [1, 2, 3], n = 3
    All subarrays :  [1], [1, 2], [1, 2, 3], 
                     [2], [2, 3], [3]
    here first element 'arr[0]' appears 3 times    
         second element 'arr[1]' appears 4 times  
         third element 'arr[2]' appears 3 times
    
    Every element arr[i] appears in two types of subsets:
    i)  In sybarrays beginning with arr[i]. There are 
        (n-i) such subsets. For example [2] appears
        in [2] and [2, 3].
    ii) In (n-i)*i subarrays where this element is not
        first element. For example [2] appears in 
        [1, 2] and [1, 2, 3].
    
    Total of above (i) and (ii) = (n-i) + (n-i)*i 
                                = (n-i)(i+1)
                                      
    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 + 2*4 + 3*3 
    = 20

        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 all subarray sum
            return result ;
        }
    

      

  • 相关阅读:
    ADT中通过Android SDK Manager去安装x86的image时无法下载
    javadoc 生成文档注释
    char类型的字节数
    win7下JDK环境变量设置方法
    artTemplate模板引擎
    输入与输出
    后台弹出JS类
    数据库主键的设计和思考
    Windows下批处理执行MySQL脚本文件
    You know元音字母吗?
  • 原文地址:https://www.cnblogs.com/apanda009/p/7701784.html
Copyright © 2011-2022 走看看