📌  相关文章
📜  计算可能的去除量,以使奇数和偶数索引元素之和等于K的绝对差

📅  最后修改于: 2021-05-17 02:13:35             🧑  作者: Mango

给定由N个整数和整数K组成的数组arr [] ,任务是查找从给定的位置一次删除任何一个元素后,奇数和偶数索引处的元素之和之间的绝对差为K的次数。大批。

例子:

天真的方法:最简单的方法是逐个删除每个数组元素,并在每次删除之后,检查奇数和偶数索引处的元素之和之间的绝对差是否为K。如果发现为真,则增加计数。遍历数组后,输出count的值。

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

高效方法:为了优化上述方法,我们的想法是使用Prefix Sum和Suffix Sum数组。请按照以下步骤解决问题:

  • 将大小为(N + 2)的两个数组prefixSum []suffixSum []初始化为0,以分别在奇数和偶数索引处存储元素的前缀和后缀和。
  • 从索引2开始,将数组arr []的元素的前缀和存储在数组prefixSum []中的奇数和偶数索引处。
  • 从索引(N +1)开始,将数组arr []的元素的后缀和存储在数组suffixSum []中的奇数和偶数索引处。
  • 将变量计数初始化为0,以存储奇数和偶数索引处的元素之和之间的绝对差为K的次数。
  • 遍历给定数组arr []并按照以下条件递增计数:
    • 如果当前元素arr [i]被删除,则检查(prefixSum [i – 1] +后缀[i + 2])的绝对差和
      (前缀[i – 2] +后缀[i + 1])是否为K。
    • 如果发现差为K,则将计数增加1 ,否则检查下一个元素。
  • 检查条件是否分别取出0第一元件之后真,并相应地增加计数。
  • 经过上述步骤后,该计数给出的元素总数将被删除。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include "bits/stdc++.h"
using namespace std;
 
// Function to check if difference
// between the sum of odd and even
// indexed elements after removing
// the first element is K or not
int findCount0th(vector& arr,
                 int N, int K)
{
    // Stores the sum of elements
    // at odd and even indices
    int oddsum = 0, evensum = 0;
 
    for (int i = 1; i < N; i += 2) {
        oddsum += arr[i];
    }
    for (int i = 2; i < N; i += 2) {
        evensum += arr[i];
    }
 
    // Return 1 if difference is K
    if (abs(oddsum - evensum) == K)
        return 1;
    else
        return 0;
}
 
// Function to check if difference
// between the sum of odd and even
// indexed elements after removing
// the second element is K or not
int findCount1st(vector& arr,
                 int N, int K)
{
    // Stores the sum of elements
    // at odd and even indices
    int evensum = arr[0], oddsum = 0;
 
    for (int i = 3; i < N; i += 2) {
        evensum += arr[i];
    }
    for (int i = 2; i < N; i += 2) {
        oddsum += arr[i];
    }
 
    // Return 1 if difference is K
    if (abs(oddsum - evensum) == K)
        return 1;
    else
        return 0;
}
 
// Function to count number of elements
// to be removed to make sum of
// differences between odd and even
// indexed elements equal to K
int countTimes(vector& arr, int K)
{
    // Size of given array
    int N = (int)arr.size();
 
    // Base Conditions
    if (N == 1)
        return 1;
    if (N < 3)
        return 0;
    if (N == 3) {
        int cnt = 0;
        cnt += (abs(arr[0] - arr[1])
                        == K
                    ? 1
                    : 0)
 
               + (abs(arr[2] - arr[1])
                          == K
                      ? 1
                      : 0)
 
               + (abs(arr[0] - arr[2])
                          == K
                      ? 1
                      : 0);
 
        return cnt;
    }
 
    // Stores prefix and suffix sums
    vector prefix(N + 2, 0);
    vector suffix(N + 2, 0);
 
    // Base assignments
    prefix[0] = arr[0];
    prefix[1] = arr[1];
    suffix[N - 1] = arr[N - 1];
    suffix[N - 2] = arr[N - 2];
 
    // Store prefix sums of even
    // indexed elements
    for (int i = 2; i < N; i += 2) {
        prefix[i] = arr[i] + prefix[i - 2];
    }
 
    // Store prefix sums of odd
    // indexed elements
    for (int i = 3; i < N; i += 2) {
        prefix[i] = arr[i] + prefix[i - 2];
    }
 
    // Similarly, store suffix sums of
    // elements at even and odd indices
    for (int i = N - 3; i >= 0; i -= 2) {
        suffix[i] = arr[i] + suffix[i + 2];
    }
    for (int i = N - 4; i >= 0; i -= 2) {
        suffix[i] = arr[i] + suffix[i + 2];
    }
 
    // Stores the count of possible removals
    int count = 0;
 
    // Traverse and remove the ith element
    for (int i = 2; i < N; i++) {
 
        // If the current element is
        // excluded, then previous index
        // (i - 1) points to (i + 2)
        // and (i - 2) points to (i + 1)
        if (abs(prefix[i - 1] + suffix[i + 2]
                - prefix[i - 2] - suffix[i + 1])
            == K) {
            count++;
        }
    }
 
    // Find count when 0th element is removed
    count += findCount0th(arr, N, K);
 
    // Find count when 1st element is removed
    count += findCount1st(arr, N, K);
 
    // Count gives the required answer
    return count;
}
 
// Driver Code
int main()
{
    vector arr = { 1, 2, 4, 5, 6 };
    int K = 2;
 
    // Function call
    cout << countTimes(arr, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
  
class GFG{
 
// Function to check if difference
// between the sum of odd and even
// indexed elements after removing
// the first element is K or not
static int findCount0th(int[] arr,
                 int N, int K)
{
    // Stores the sum of elements
    // at odd and even indices
    int oddsum = 0, evensum = 0;
  
    for (int i = 1; i < N; i += 2) {
        oddsum += arr[i];
    }
    for (int i = 2; i < N; i += 2) {
        evensum += arr[i];
    }
  
    // Return 1 if difference is K
    if (Math.abs(oddsum - evensum) == K)
        return 1;
    else
        return 0;
}
  
// Function to check if difference
// between the sum of odd and even
// indexed elements after removing
// the second element is K or not
static int findCount1st(int[] arr,
                 int N, int K)
{
    // Stores the sum of elements
    // at odd and even indices
    int evensum = arr[0], oddsum = 0;
  
    for (int i = 3; i < N; i += 2) {
        evensum += arr[i];
    }
    for (int i = 2; i < N; i += 2) {
        oddsum += arr[i];
    }
  
    // Return 1 if difference is K
    if (Math.abs(oddsum - evensum) == K)
        return 1;
    else
        return 0;
}
  
// Function to count number of elements
// to be removed to make sum of
// differences between odd and even
// indexed elements equal to K
static int countTimes(int[] arr, int K)
{
    // Size of given array
    int N = (int)arr.length;
  
    // Base Conditions
    if (N == 1)
        return 1;
    if (N < 3)
        return 0;
    if (N == 3) {
        int cnt = 0;
        cnt += (Math.abs(arr[0] - arr[1])
                        == K
                    ? 1
                    : 0)
  
               + (Math.abs(arr[2] - arr[1])
                          == K
                      ? 1
                      : 0)
  
               + (Math.abs(arr[0] - arr[2])
                          == K
                      ? 1
                      : 0);
  
        return cnt;
    }
  
    // Stores prefix and suffix sums
    int[]  prefix = new int[N + 2];
    int[]  suffix = new int[N + 2];
    Arrays.fill(prefix, 0);
    Arrays.fill(suffix, 0);
  
    // Base assignments
    prefix[0] = arr[0];
    prefix[1] = arr[1];
    suffix[N - 1] = arr[N - 1];
    suffix[N - 2] = arr[N - 2];
  
    // Store prefix sums of even
    // indexed elements
    for (int i = 2; i < N; i += 2) {
        prefix[i] = arr[i] + prefix[i - 2];
    }
  
    // Store prefix sums of odd
    // indexed elements
    for (int i = 3; i < N; i += 2) {
        prefix[i] = arr[i] + prefix[i - 2];
    }
  
    // Similarly, store suffix sums of
    // elements at even and odd indices
    for (int i = N - 3; i >= 0; i -= 2) {
        suffix[i] = arr[i] + suffix[i + 2];
    }
    for (int i = N - 4; i >= 0; i -= 2) {
        suffix[i] = arr[i] + suffix[i + 2];
    }
  
    // Stores the count of possible removals
    int count = 0;
  
    // Traverse and remove the ith element
    for (int i = 2; i < N; i++) {
  
        // If the current element is
        // excluded, then previous index
        // (i - 1) points to (i + 2)
        // and (i - 2) points to (i + 1)
        if (Math.abs(prefix[i - 1] + suffix[i + 2]
                - prefix[i - 2] - suffix[i + 1])
            == K) {
            count++;
        }
    }
  
    // Find count when 0th element is removed
    count += findCount0th(arr, N, K);
  
    // Find count when 1st element is removed
    count += findCount1st(arr, N, K);
  
    // Count gives the required answer
    return count;
}
 
// Driver code
public static void main(String[] args)
{
    int[] arr = { 1, 2, 4, 5, 6 };
    int K = 2;
  
    // Function call
    System.out.println(countTimes(arr, K));
}
}
 
// This code is contributed by code_hunt.


Python3
# Python3 program for the above approach
 
# Function to check if difference
# between the sum of odd and even
# indexed elements after removing
# the first element is K or not
def findCount0th(arr, N, K):
     
    # Stores the sum of elements
    # at odd and even indices
    oddsum = 0
    evensum = 0
 
    for i in range(1, N, 2):
        oddsum += arr[i]
     
    for i in range(2, N, 2):
        evensum += arr[i]
 
    # Return 1 if difference is K
    if (abs(oddsum - evensum) == K):
        return 1
    else:
        return 0
 
# Function to check if difference
# between the sum of odd and even
# indexed elements after removing
# the second element is K or not
def findCount1st(arr, N, K):
     
    # Stores the sum of elements
    # at odd and even indices
    evensum = arr[0]
    oddsum = 0
 
    for i in range(3, N, 2):
        evensum += arr[i]
     
    for i in range(2, N, 2):
        oddsum += arr[i]
     
    # Return 1 if difference is K
    if (abs(oddsum - evensum) == K):
        return 1
    else:
        return 0
 
# Function to count number of elements
# to be removed to make sum of
# differences between odd and even
# indexed elements equal to K
def countTimes(arr, K):
 
    # Size of given array
    N = len(arr)
 
    # Base Conditions
    if (N == 1):
        return 1
         
    if (N < 3):
        return 0
         
    if (N == 3):
        cnt = 0
         
        if abs(arr[0] - arr[1]) == K:
            cnt += 1
         
        if abs(arr[2] - arr[1]) == K:
            cnt += 1
     
        if abs(arr[0] - arr[2]) == K:
            cnt += 1
             
        return cnt
 
    # Stores prefix and suffix sums
    prefix = [0] * (N + 2)
    suffix = [0] * (N + 2)
 
    # Base assignments
    prefix[0] = arr[0]
    prefix[1] = arr[1]
    suffix[N - 1] = arr[N - 1]
    suffix[N - 2] = arr[N - 2]
 
    # Store prefix sums of even
    # indexed elements
    for i in range(2, N, 2):
        prefix[i] = arr[i] + prefix[i - 2]
 
    # Store prefix sums of odd
    # indexed elements
    for i in range(3, N, 2):
        prefix[i] = arr[i] + prefix[i - 2]
 
    # Similarly, store suffix sums of
    # elements at even and odd indices
    for i in range(N - 3, -1, -2):
        suffix[i] = arr[i] + suffix[i + 2]
 
    for i in range( N - 4, -1, -2):
        suffix[i] = arr[i] + suffix[i + 2]
 
    # Stores the count of possible removals
    count = 0
 
    # Traverse and remove the ith element
    for i in range(2, N):
 
        # If the current element is
        # excluded, then previous index
        # (i - 1) points to (i + 2)
        # and (i - 2) points to (i + 1)
        if (abs(prefix[i - 1] + suffix[i + 2] -
                prefix[i - 2] - suffix[i + 1]) == K):
            count += 1
         
    # Find count when 0th element is removed
    count += findCount0th(arr, N, K)
     
    # Find count when 1st element is removed
    count += findCount1st(arr, N, K)
 
    # Count gives the required answer
    return count
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 4, 5, 6 ]
    K = 2
 
    # Function call
    print(countTimes(arr, K))
     
# This code is contributed by AnkThon


C#
// C# program for the above approach
using System;
    
class GFG{
    
// Function to check if difference
// between the sum of odd and even
// indexed elements after removing
// the first element is K or not
static int findCount0th(int[] arr,
                        int N, int K)
{
     
    // Stores the sum of elements
    // at odd and even indices
    int oddsum = 0, evensum = 0;
   
    for(int i = 1; i < N; i += 2)
    {
        oddsum += arr[i];
    }
    for(int i = 2; i < N; i += 2)
    {
        evensum += arr[i];
    }
   
    // Return 1 if difference is K
    if (Math.Abs(oddsum - evensum) == K)
        return 1;
    else
        return 0;
}
   
// Function to check if difference
// between the sum of odd and even
// indexed elements after removing
// the second element is K or not
static int findCount1st(int[] arr,
                 int N, int K)
{
     
    // Stores the sum of elements
    // at odd and even indices
    int evensum = arr[0], oddsum = 0;
   
    for(int i = 3; i < N; i += 2)
    {
        evensum += arr[i];
    }
    for(int i = 2; i < N; i += 2)
    {
        oddsum += arr[i];
    }
   
    // Return 1 if difference is K
    if (Math.Abs(oddsum - evensum) == K)
        return 1;
    else
        return 0;
}
   
// Function to count number of elements
// to be removed to make sum of
// differences between odd and even
// indexed elements equal to K
static int countTimes(int[] arr, int K)
{
     
    // Size of given array
    int N = (int)arr.Length;
   
    // Base Conditions
    if (N == 1)
        return 1;
    if (N < 3)
        return 0;
    if (N == 3)
    {
        int cnt = 0;
        cnt += (Math.Abs(arr[0] - arr[1]) == K ? 1 : 0) +
               (Math.Abs(arr[2] - arr[1]) == K ? 1 : 0) +
               (Math.Abs(arr[0] - arr[2]) == K ? 1 : 0);
   
        return cnt;
    }
   
    // Stores prefix and suffix sums
    int[]  prefix = new int[N + 2];
    int[]  suffix = new int[N + 2];
     
    for(int i = 0; i < N + 2; i++)
    {
        prefix[i] = 0;
    }
    for(int i = 0; i < N + 2; i++)
    {
        suffix[i] = 0;
    }
   
    // Base assignments
    prefix[0] = arr[0];
    prefix[1] = arr[1];
    suffix[N - 1] = arr[N - 1];
    suffix[N - 2] = arr[N - 2];
   
    // Store prefix sums of even
    // indexed elements
    for(int i = 2; i < N; i += 2)
    {
        prefix[i] = arr[i] + prefix[i - 2];
    }
   
    // Store prefix sums of odd
    // indexed elements
    for(int i = 3; i < N; i += 2)
    {
        prefix[i] = arr[i] + prefix[i - 2];
    }
   
    // Similarly, store suffix sums of
    // elements at even and odd indices
    for(int i = N - 3; i >= 0; i -= 2)
    {
        suffix[i] = arr[i] + suffix[i + 2];
    }
    for(int i = N - 4; i >= 0; i -= 2)
    {
        suffix[i] = arr[i] + suffix[i + 2];
    }
   
    // Stores the count of possible removals
    int count = 0;
   
    // Traverse and remove the ith element
    for(int i = 2; i < N; i++)
    {
         
        // If the current element is
        // excluded, then previous index
        // (i - 1) points to (i + 2)
        // and (i - 2) points to (i + 1)
        if (Math.Abs(prefix[i - 1] + suffix[i + 2] -
                     prefix[i - 2] - suffix[i + 1]) == K)
        {
            count++;
        }
    }
   
    // Find count when 0th element is removed
    count += findCount0th(arr, N, K);
   
    // Find count when 1st element is removed
    count += findCount1st(arr, N, K);
   
    // Count gives the required answer
    return count;
}
    
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 4, 5, 6 };
    int K = 2;
   
    // Function call
    Console.WriteLine(countTimes(arr, K));
}
}
 
// This code is contributed by susmitakundugoaldanga


输出:
2

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