📌  相关文章
📜  通过将每个数组元素替换为0来计算将数组拆分为两个相等和子数组的方法

📅  最后修改于: 2021-04-26 05:08:26             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,任务是计算将单个数组元素更改为0后将数组拆分为两个相等总和的子数组的方式的数量。

例子:

天真的方法:解决问题的最简单方法是遍历数组,将每个数组元素arr [i]转换为0,并计算将修改后的数组分为两个总和相等的子数组的方法数量。

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

高效方法:为了优化上述方法,该思想基于以下观察结果:

对于[0,N – 1]范围内的每个索引,通过使用上述过程使任何元素等于0 ,可以通过将当前索引视为分裂点来获得路总数。请按照以下步骤解决问题:

  • 初始化变量计数0来存储所希望的结果,并用0 prefix_sum的到前缀总和和suffixSum存储与0来存储后缀总和。
  • 初始化哈希图prefixCountsuffixCount,以将元素的计数存储在前缀和后缀数组中。
  • 遍历arr []并更新suffixCount中每个元素的频率。
  • 使用变量i[0,N – 1]范围内遍历arr []。
    • arr [i]添加到prefixCount哈希图中,并将其从suffixCount中删除。
    • prefixSum和组suffixSum添加ARR [I]到阵列的总和的差 prefixSum
    • 将子数组总和之间的差存储在变量dif = prefix_sum – suffixSum中
    • 将分割i索引的方式的数目存储在number_of_subarray_at_i_split中,该数目等于prefixCountsuffixCount的总和。
    • 通过将number_of_subarray_at_i_split添加到计数来更新计数
  • 完成上述步骤后,将count的值打印为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find number of ways to
// split array into 2 subarrays having
// equal sum by changing element to 0 once
int countSubArrayRemove(int arr[], int N)
{
    // Stores the count of elements
    // in prefix and suffix of
    // array elements
    unordered_map
        prefix_element_count,
        suffix_element_count;
 
    // Stores the sum of array
    int total_sum_of_elements = 0;
 
    // Traverse the array
    for (int i = N - 1; i >= 0; i--) {
 
        total_sum_of_elements += arr[i];
 
        // Increase the frequency of
        // current element in suffix
        suffix_element_count[arr[i]]++;
    }
 
    // Stores prefix sum upto index i
    int prefix_sum = 0;
 
    // Stores sum of suffix of index i
    int suffix_sum = 0;
 
    // Stores the desired result
    int count_subarray_equal_sum = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Modify prefix sum
        prefix_sum += arr[i];
 
        // Add arr[i] to prefix map
        prefix_element_count[arr[i]]++;
 
        // Calculate suffix sum by
        // subtracting prefix sum
        // from total sum of elements
        suffix_sum = total_sum_of_elements
                     - prefix_sum;
 
        // Remove arr[i] from suffix map
        suffix_element_count[arr[i]]--;
 
        // Store the difference
        // between the subarrays
        int difference = prefix_sum
                         - suffix_sum;
 
        // Count number of ways to split
        // the array at index i such that
        // subarray sums are equal
        int number_of_subarray_at_i_split
            = prefix_element_count[difference]
              + suffix_element_count[-difference];
 
        // Update the final result
        count_subarray_equal_sum
            += number_of_subarray_at_i_split;
    }
 
    // Return the result
    return count_subarray_equal_sum;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 1, 1, 3, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countSubArrayRemove(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to find number of ways to
// split array into 2 subarrays having
// equal sum by changing element to 0 once
static int countSubArrayRemove(int []arr, int N)
{
     
    // Stores the count of elements
    // in prefix and suffix of
    // array elements
    HashMap prefix_element_count = new HashMap();
    HashMap suffix_element_count = new HashMap();
 
    // Stores the sum of array
    int total_sum_of_elements = 0;
 
    // Traverse the array
    for(int i = N - 1; i >= 0; i--)
    {
        total_sum_of_elements += arr[i];
 
        // Increase the frequency of
        // current element in suffix
        if (!suffix_element_count.containsKey(arr[i]))
            suffix_element_count.put(arr[i], 1);
        else
            suffix_element_count.put(arr[i],
              suffix_element_count.get(arr[i]) + 1);
    }
 
    // Stores prefix sum upto index i
    int prefix_sum = 0;
 
    // Stores sum of suffix of index i
    int suffix_sum = 0;
 
    // Stores the desired result
    int count_subarray_equal_sum = 0;
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Modify prefix sum
        prefix_sum += arr[i];
 
        // Add arr[i] to prefix map
       if (!prefix_element_count.containsKey(arr[i]))
           prefix_element_count.put(arr[i], 1);
       else
           prefix_element_count.put(arr[i],
           prefix_element_count.get(arr[i]) + 1);
 
        // Calculate suffix sum by
        // subtracting prefix sum
        // from total sum of elements
        suffix_sum = total_sum_of_elements -
                     prefix_sum;
 
        // Remove arr[i] from suffix map
        if (!suffix_element_count.containsKey(arr[i]))
            suffix_element_count.put(arr[i], 0);
        else
            suffix_element_count.put(arr[i],
            suffix_element_count.get(arr[i]) - 1);
 
        // Store the difference
        // between the subarrays
        int difference = prefix_sum -
                         suffix_sum;
 
        // Count number of ways to split
        // the array at index i such that
        // subarray sums are equal
        int number_of_subarray_at_i_split = 0;
        if (prefix_element_count.containsKey(difference))
            number_of_subarray_at_i_split =
            prefix_element_count.get(difference);
        if (suffix_element_count.containsKey(-difference))
            number_of_subarray_at_i_split +=
            suffix_element_count.get(-difference);
 
        // Update the final result
        count_subarray_equal_sum +=
        number_of_subarray_at_i_split;
    }
 
    // Return the result
    return count_subarray_equal_sum;
}  
 
// Driver Code
public static void main(String args[])
{
    int []arr = { 1, 2, 1, 1, 3, 1 };
    int N = arr.length;
     
    // Function Call
    System.out.println(countSubArrayRemove(arr, N));
}
}
 
// This code is contributed by Stream_Cipher


Python3
# Python3 program for the above approach
 
# Function to find number of ways to
# split array into 2 subarrays having
# equal sum by changing element to 0 once
def countSubArrayRemove(arr, N):
     
    # Stores the count of elements
    # in prefix and suffix of
    # array elements
    prefix_element_count = {}
    suffix_element_count = {}
 
    # Stores the sum of array
    total_sum_of_elements = 0
 
    # Traverse the array
    i = N - 1
    while (i >= 0):
        total_sum_of_elements += arr[i]
 
        # Increase the frequency of
        # current element in suffix
        suffix_element_count[arr[i]] = suffix_element_count.get(
            arr[i], 0) + 1
             
        i -= 1
 
    # Stores prefix sum upto index i
    prefix_sum = 0
 
    # Stores sum of suffix of index i
    suffix_sum = 0
 
    # Stores the desired result
    count_subarray_equal_sum = 0
 
    # Traverse the array
    for i in range(N):
         
        # Modify prefix sum
        prefix_sum += arr[i]
 
        # Add arr[i] to prefix map
        prefix_element_count[arr[i]] = prefix_element_count.get(
            arr[i], 0) + 1
 
        # Calculate suffix sum by
        # subtracting prefix sum
        # from total sum of elements
        suffix_sum = total_sum_of_elements - prefix_sum
 
        # Remove arr[i] from suffix map
        suffix_element_count[arr[i]] = suffix_element_count.get(
            arr[i], 0) - 1
 
        # Store the difference
        # between the subarrays
        difference = prefix_sum - suffix_sum
 
        # Count number of ways to split
        # the array at index i such that
        # subarray sums are equal
        number_of_subarray_at_i_split = (prefix_element_count.get(
                                             difference, 0) +
                                         suffix_element_count.get(
                                            -difference, 0))
 
        # Update the final result
        count_subarray_equal_sum += number_of_subarray_at_i_split
 
    # Return the result
    return count_subarray_equal_sum
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 1, 1, 3, 1 ]
    N =  len(arr)
 
    # Function Call
    print(countSubArrayRemove(arr, N))
     
# This code is contributed by SURENDRA_GANGWAR


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find number of ways to
// split array into 2 subarrays having
// equal sum by changing element to 0 once
static int countSubArrayRemove(int []arr, int N)
{
     
    // Stores the count of elements
    // in prefix and suffix of
    // array elements
    Dictionary prefix_element_count = new Dictionary ();
    Dictionarysuffix_element_count = new Dictionary ();
 
    // Stores the sum of array
    int total_sum_of_elements = 0;
 
    // Traverse the array
    for(int i = N - 1; i >= 0; i--)
    {
        total_sum_of_elements += arr[i];
 
        // Increase the frequency of
        // current element in suffix
        if (!suffix_element_count.ContainsKey(arr[i]))
            suffix_element_count[arr[i]] = 1;
        else
            suffix_element_count[arr[i]]++;
    }
 
    // Stores prefix sum upto index i
    int prefix_sum = 0;
 
    // Stores sum of suffix of index i
    int suffix_sum = 0;
 
    // Stores the desired result
    int count_subarray_equal_sum = 0;
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Modify prefix sum
        prefix_sum += arr[i];
 
        // Add arr[i] to prefix map
       if (!prefix_element_count.ContainsKey(arr[i]))
           prefix_element_count[arr[i]] = 1;
       else
           prefix_element_count[arr[i]]++;
 
        // Calculate suffix sum by
        // subtracting prefix sum
        // from total sum of elements
        suffix_sum = total_sum_of_elements -
                     prefix_sum;
 
        // Remove arr[i] from suffix map
        if (!suffix_element_count.ContainsKey(arr[i]))
            suffix_element_count[arr[i]] = 0;
        else
            suffix_element_count[arr[i]]-= 1;
 
        // Store the difference
        // between the subarrays
        int difference = prefix_sum -
                         suffix_sum;
 
        // Count number of ways to split
        // the array at index i such that
        // subarray sums are equal
        int number_of_subarray_at_i_split = 0;
        if (prefix_element_count.ContainsKey(difference))
            number_of_subarray_at_i_split
            = prefix_element_count[difference];
        if (suffix_element_count.ContainsKey(-difference))
            number_of_subarray_at_i_split
            += suffix_element_count[-difference];
 
        // Update the final result
        count_subarray_equal_sum
            += number_of_subarray_at_i_split;
    }
 
    // Return the result
    return count_subarray_equal_sum;
}
 
// Driver Code
public static void Main(string []args)
{
    int []arr = { 1, 2, 1, 1, 3, 1 };
    int N = arr.Length;
 
    // Function Call
    Console.Write(countSubArrayRemove(arr, N));
}
}
 
// This code is contributed by chitranayal


输出:
6

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