📌  相关文章
📜  所有奇数长度子数组的总和

📅  最后修改于: 2021-04-21 22:08:06             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,任务是找到奇数长度的所有可能子数组的所有元素的总和。

例子:

天真的方法:最简单的方法是从给定的数组中生成所有可能的奇数长度的子数组,并找到所有这些子数组的总和。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to calculate the sum
// of all odd length subarrays
int OddLengthSum(vector& arr)
{
    // Stores the sum
    int sum = 0;
 
    // Size of array
    int l = arr.size();
 
    // Traverse the array
    for (int i = 0; i < l; i++) {
 
        // Generate all subarray of
        // odd length
        for (int j = i; j < l; j += 2) {
 
            for (int k = i; k <= j; k++) {
 
                // Add the element to sum
                sum += arr[k];
            }
        }
    }
 
    // Return the final sum
    return sum;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    vector arr = { 1, 5, 3, 1, 2 };
 
    // Function Call
    cout << OddLengthSum(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.Arrays;
 
class GFG{
  
// Function to calculate the sum
// of all odd length subarrays
static int OddLengthSum(int[] arr)
{
     
    // Stores the sum
    int sum = 0;
  
    // Size of array
    int l = arr.length;
  
    // Traverse the array
    for(int i = 0; i < l; i++)
    {
         
        // Generate all subarray of
        // odd length
        for(int j = i; j < l; j += 2)
        {
            for(int k = i; k <= j; k++)
            {
                 
                // Add the element to sum
                sum += arr[k];
            }
        }
    }
     
    // Return the final sum
    return sum;
}
  
// Driver Code
public static void main (String[] args)
{
     
    // Given array arr[]
    int[] arr = { 1, 5, 3, 1, 2 };
  
    // Function call
    System.out.print(OddLengthSum(arr));
}
}
 
// This code is contributed by sanjoy_62


Python3
# Python3 program for the above approach
  
# Function to calculate the sum
# of all odd length subarrays
def OddLengthSum(arr):
     
    # Stores the sum
    sum = 0
  
    # Size of array
    l = len(arr)
  
    # Traverse the array
    for i in range(l):
  
        # Generate all subarray of
        # odd length
        for j in range(i, l, 2):
            for k in range(i, j + 1, 1):
  
                # Add the element to sum
                sum += arr[k]
             
    # Return the final sum
    return sum
 
# Driver Code
 
# Given array arr[]
arr = [ 1, 5, 3, 1, 2 ]
  
# Function call
print(OddLengthSum(arr))
 
# This code is contributed by sanjoy_62


C#
// C# program for the above approach
using System;
 
class GFG{
  
// Function to calculate the sum
// of all odd length subarrays
static int OddLengthSum(int[] arr)
{
     
    // Stores the sum
    int sum = 0;
  
    // Size of array
    int l = arr.Length;
  
    // Traverse the array
    for(int i = 0; i < l; i++)
    {
         
        // Generate all subarray of
        // odd length
        for(int j = i; j < l; j += 2)
        {
            for(int k = i; k <= j; k++)
            {
                 
                // Add the element to sum
                sum += arr[k];
            }
        }
    }
  
    // Return the final sum
    return sum;
}
  
// Driver Code
public static void Main ()
{
     
    // Given array arr[]
    int[] arr = { 1, 5, 3, 1, 2 };
  
    // Function call
    Console.Write(OddLengthSum(arr));
}
}
 
// This code is contributed by sanjoy_62


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function that finds the sum of all
// the element of subarrays of odd length
int OddLengthSum(vector& arr)
{
    // Stores the sum
    int sum = 0;
 
    // Size of array
    int l = arr.size();
 
    // Traverse the given array arr[]
    for (int i = 0; i < l; i++) {
 
        // Add to the sum for each
        // contribution of the arr[i]
        sum += (((i + 1)
                     * (l - i)
                 + 1)
                / 2)
               * arr[i];
    }
 
    // Return the final sum
    return sum;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    vector arr = { 1, 5, 3, 1, 2 };
 
    // Function Call
    cout << OddLengthSum(arr);
 
    return 0;
}


Java
// Java program for the above approach
class GFG{
 
// Function that finds the sum of all
// the element of subarrays of odd length
static int OddLengthSum(int []arr)
{
     
    // Stores the sum
    int sum = 0;
 
    // Size of array
    int l = arr.length;
 
    // Traverse the given array arr[]
    for(int i = 0; i < l; i++)
    {
         
        // Add to the sum for each
        // contribution of the arr[i]
        sum += (((i + 1) * (l - i) +
                 1) / 2) * arr[i];
    }
 
    // Return the final sum
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int []arr = { 1, 5, 3, 1, 2 };
 
    // Function call
    System.out.print(OddLengthSum(arr));
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
 
# Function that finds the sum of all
# the element of subarrays of odd length
def OddLengthSum(arr):
 
    # Stores the sum
    Sum = 0
 
    # Size of array
    l = len(arr)
 
    # Traverse the given array arr[]
    for i in range(l):
     
        # Add to the sum for each
        # contribution of the arr[i]
        Sum += ((((i + 1) *
                  (l - i) +
                 1) // 2) * arr[i])
     
    # Return the final sum
    return Sum
 
# Driver code
 
# Given array arr[]
arr = [ 1, 5, 3, 1, 2 ]
 
# Function call
print(OddLengthSum(arr))
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for
// the above approach
using System;
class GFG{
 
// Function that finds the
// sum of all the element of
// subarrays of odd length
static int OddLengthSum(int []arr)
{
  // Stores the sum
  int sum = 0;
 
  // Size of array
  int l = arr.Length;
 
  // Traverse the given array []arr
  for(int i = 0; i < l; i++)
  {
    // Add to the sum for each
    // contribution of the arr[i]
    sum += (((i + 1) *
             (l - i) + 1) / 2) * arr[i];
  }
 
  // Return the readonly sum
  return sum;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  int []arr = {1, 5, 3, 1, 2};
 
  // Function call
  Console.Write(OddLengthSum(arr));
}
}
 
// This code is contributed by Rajput-Ji


输出
48

时间复杂度: O(N 3 )
辅助空间: O(1)

高效方法:为优化上述方法,其思想是在生成所有奇数长度的子数组后观察以下模式:

  • 对于索引idx处的任何元素,其左侧都有(idx +1)个选择,右侧有(N – idx)个选择。
  • 因此,对于任何元素arr [i] ,在所有子数组中arr [i]的计数均为(i +1)*(N – i)
  • 因此,对于元素arr [i] ,存在((i + 1)*(N – i)+1)/ 2个具有奇数长度的子数组。
  • 最后, arr [i]的总和为((i + 1)*(n – i)+1)/ 2个频率。

因此,要找到奇数长度的所有子数组的所有元素的总和,我们的想法是遍历该数组,并对每个i数组元素,添加[ (((i + 1)*(n – i)+ 1) / 2] * arr [i]

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function that finds the sum of all
// the element of subarrays of odd length
int OddLengthSum(vector& arr)
{
    // Stores the sum
    int sum = 0;
 
    // Size of array
    int l = arr.size();
 
    // Traverse the given array arr[]
    for (int i = 0; i < l; i++) {
 
        // Add to the sum for each
        // contribution of the arr[i]
        sum += (((i + 1)
                     * (l - i)
                 + 1)
                / 2)
               * arr[i];
    }
 
    // Return the final sum
    return sum;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    vector arr = { 1, 5, 3, 1, 2 };
 
    // Function Call
    cout << OddLengthSum(arr);
 
    return 0;
}

Java

// Java program for the above approach
class GFG{
 
// Function that finds the sum of all
// the element of subarrays of odd length
static int OddLengthSum(int []arr)
{
     
    // Stores the sum
    int sum = 0;
 
    // Size of array
    int l = arr.length;
 
    // Traverse the given array arr[]
    for(int i = 0; i < l; i++)
    {
         
        // Add to the sum for each
        // contribution of the arr[i]
        sum += (((i + 1) * (l - i) +
                 1) / 2) * arr[i];
    }
 
    // Return the final sum
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int []arr = { 1, 5, 3, 1, 2 };
 
    // Function call
    System.out.print(OddLengthSum(arr));
}
}
 
// This code is contributed by Amit Katiyar

Python3

# Python3 program for the above approach
 
# Function that finds the sum of all
# the element of subarrays of odd length
def OddLengthSum(arr):
 
    # Stores the sum
    Sum = 0
 
    # Size of array
    l = len(arr)
 
    # Traverse the given array arr[]
    for i in range(l):
     
        # Add to the sum for each
        # contribution of the arr[i]
        Sum += ((((i + 1) *
                  (l - i) +
                 1) // 2) * arr[i])
     
    # Return the final sum
    return Sum
 
# Driver code
 
# Given array arr[]
arr = [ 1, 5, 3, 1, 2 ]
 
# Function call
print(OddLengthSum(arr))
 
# This code is contributed by divyeshrabadiya07

C#

// C# program for
// the above approach
using System;
class GFG{
 
// Function that finds the
// sum of all the element of
// subarrays of odd length
static int OddLengthSum(int []arr)
{
  // Stores the sum
  int sum = 0;
 
  // Size of array
  int l = arr.Length;
 
  // Traverse the given array []arr
  for(int i = 0; i < l; i++)
  {
    // Add to the sum for each
    // contribution of the arr[i]
    sum += (((i + 1) *
             (l - i) + 1) / 2) * arr[i];
  }
 
  // Return the readonly sum
  return sum;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  int []arr = {1, 5, 3, 1, 2};
 
  // Function call
  Console.Write(OddLengthSum(arr));
}
}
 
// This code is contributed by Rajput-Ji
输出
48

时间复杂度: O(N)
辅助空间: O(1)