📌  相关文章
📜  给定数组的前缀和后缀总和相等的索引计数

📅  最后修改于: 2022-05-13 01:56:06.355000             🧑  作者: Mango

给定数组的前缀和后缀总和相等的索引计数

给定一个整数数组arr[] ,任务是找到前缀和和后缀和相等的索引数。

例子:

天真的方法:给定的问题可以通过从左到右遍历数组arr并计算前缀总和直到该索引然后从右到左迭代数组arr并计算后缀总和然后检查前缀和后缀总和是否相等来解决。
时间复杂度: O(N^2)

方法:上述方法可以通过迭代数组arr两次来优化。这个想法是预先计算后缀总和作为总子数组总和。然后再次迭代数组以计算每个索引处的前缀总和,然后比较前缀和后缀总和并更新后缀总和。请按照以下步骤解决问题:

  • 将变量res初始化为零以计算答案
  • 初始化一个变量sufSum来存储后缀和
  • 初始化一个变量preSum来存储前缀和
  • 遍历数组arr并将每个元素arr[i]添加到sufSum
  • 在每次迭代时再次迭代数组arr
    • 将当前元素arr[i]添加到preSum
    • 如果preSumsufSum相等,则将res的值增加 1
    • sufSum中减去当前元素arr[i]
  • 返回存储在res中的答案

下面是上述方法的实现:

C++
// C++ code for the above approach
#include 
using namespace std;
 
// Function to calculate number of
// equal prefix and suffix sums
// till the same indices
int equalSumPreSuf(int arr[], int n)
{
 
    // Initialize a variable
    // to store the result
    int res = 0;
 
    // Initialize variables to
    // calculate prefix and suffix sums
    int preSum = 0, sufSum = 0;
 
    // Length of array arr
    int len = n;
 
    // Traverse the array from right to left
    for (int i = len - 1; i >= 0; i--)
    {
 
        // Add the current element
        // into sufSum
        sufSum += arr[i];
    }
 
    // Iterate the array from left to right
    for (int i = 0; i < len; i++)
    {
 
        // Add the current element
        // into preSum
        preSum += arr[i];
 
        // If prefix sum is equal to
        // suffix sum then increment res by 1
        if (preSum == sufSum)
        {
 
            // Increment the result
            res++;
        }
 
        // Subtract the value of current
        // element arr[i] from suffix sum
        sufSum -= arr[i];
    }
 
    // Return the answer
    return res;
}
 
// Driver code
int main()
{
 
    // Initialize the array
    int arr[] = {5, 0, 4, -1, -3, 0,
                 2, -2, 0, 3, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    // Call the function and
    // print its result
    cout << (equalSumPreSuf(arr, n));
}
 
// This code is contributed by Potta Lokesh


Java
// Java implementation for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to calculate number of
    // equal prefix and suffix sums
    // till the same indices
    public static int equalSumPreSuf(int[] arr)
    {
 
        // Initialize a variable
        // to store the result
        int res = 0;
 
        // Initialize variables to
        // calculate prefix and suffix sums
        int preSum = 0, sufSum = 0;
 
        // Length of array arr
        int len = arr.length;
 
        // Traverse the array from right to left
        for (int i = len - 1; i >= 0; i--) {
 
            // Add the current element
            // into sufSum
            sufSum += arr[i];
        }
 
        // Iterate the array from left to right
        for (int i = 0; i < len; i++) {
 
            // Add the current element
            // into preSum
            preSum += arr[i];
 
            // If prefix sum is equal to
            // suffix sum then increment res by 1
            if (preSum == sufSum) {
 
                // Increment the result
                res++;
            }
 
            // Subtract the value of current
            // element arr[i] from suffix sum
            sufSum -= arr[i];
        }
 
        // Return the answer
        return res;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initialize the array
        int[] arr = { 5, 0, 4, -1, -3, 0,
                      2, -2, 0, 3, 2 };
 
        // Call the function and
        // print its result
        System.out.println(equalSumPreSuf(arr));
    }
}


Python3
# Python implementation for the above approach
 
# Function to calculate number of
# equal prefix and suffix sums
# till the same indices
from builtins import range
 
def equalSumPreSuf(arr):
   
    # Initialize a variable
    # to store the result
    res = 0;
 
    # Initialize variables to
    # calculate prefix and suffix sums
    preSum = 0;
    sufSum = 0;
 
    # Length of array arr
    length = len(arr);
 
    # Traverse the array from right to left
    for i in range(length - 1,-1,-1):
       
        # Add the current element
        # into sufSum
        sufSum += arr[i];
 
    # Iterate the array from left to right
    for i in range(length):
 
        # Add the current element
        # into preSum
        preSum += arr[i];
 
        # If prefix sum is equal to
        # suffix sum then increment res by 1
        if (preSum == sufSum):
           
            # Increment the result
            res += 1;
 
        # Subtract the value of current
        # element arr[i] from suffix sum
        sufSum -= arr[i];
 
    # Return the answer
    return res;
 
# Driver code
if __name__ == '__main__':
   
    # Initialize the array
    arr = [5, 0, 4, -1, -3, 0, 2, -2, 0, 3, 2];
 
    # Call the function and
    # prits result
    print(equalSumPreSuf(arr));
 
    # This code is contributed by 29AjayKumar


C#
// C# implementation for the above approach
using System;
class GFG
{
 
    // Function to calculate number of
    // equal prefix and suffix sums
    // till the same indices
    static int equalSumPreSuf(int[] arr)
    {
 
        // Initialize a variable
        // to store the result
        int res = 0;
 
        // Initialize variables to
        // calculate prefix and suffix sums
        int preSum = 0, sufSum = 0;
 
        // Length of array arr
        int len = arr.Length;
 
        // Traverse the array from right to left
        for (int i = len - 1; i >= 0; i--) {
 
            // Add the current element
            // into sufSum
            sufSum += arr[i];
        }
 
        // Iterate the array from left to right
        for (int i = 0; i < len; i++) {
 
            // Add the current element
            // into preSum
            preSum += arr[i];
 
            // If prefix sum is equal to
            // suffix sum then increment res by 1
            if (preSum == sufSum) {
 
                // Increment the result
                res++;
            }
 
            // Subtract the value of current
            // element arr[i] from suffix sum
            sufSum -= arr[i];
        }
 
        // Return the answer
        return res;
    }
 
    // Driver code
    public static void Main()
    {
 
        // Initialize the array
        int[] arr = { 5, 0, 4, -1, -3, 0,
                      2, -2, 0, 3, 2 };
 
        // Call the function and
        // print its result
        Console.Write(equalSumPreSuf(arr));
    }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


输出
3

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