Given an array arr[] of integers, the task is to find the total count of subarrays such that the sum of elements at even position and sum of elements at the odd positions are equal.

Examples:

Input:_ arr[] = {1, 2, 3, 4, 1}_

Output:_ 1_

_Explanation: _

{3, 4, 1} is the only subarray in which sum of elements at even position {3, 1} = sum of element at odd position {4}

Input:_ arr[] = {2, 4, 6, 4, 2}_

Output:_ 2_

_Explanation: _

There are two subarrays {2, 4, 6, 4} and {4, 6, 4, 2}.

Approach: The idea is to generate all possible subarrays. For each subarray formed find the sum of the elements at even index and subtract the elements at odd index. If the sum is 0, count this subarray else check for the next subarray.

Below is the implementation of the above approach:

  • Java

// Java program for the above approach

**import** java.util.*;

**class** GFG {

// Function to count subarrays in

// which sum of elements at even

// and odd positions are equal

**static** **void** countSubarrays(``**int** arr[],

**int** n)

{

// Initialize variables

**int** count = 0``;

// Iterate over the array

**for** (``**int** i = 0``; i < n; i++) {

**int** sum = 0``;

**for** (``**int** j = i; j < n; j++) {

// Check if position is

// even then add to sum

// then add it to sum

**if** ((j - i) % 2 == 0``)

sum += arr[j];

// else subtract it to sum

**else**

sum -= arr[j];

// Increment the count

// if the sum equals 0

**if** (sum == 0``)

count++;

}

}

// Print the count of subarrays

System.out.println(count);

}

// Driver Code

**public** **static** **void**

main(String[] args)

{

// Given array arr[]

**int** arr[] = { 2``, 4``, 6``, 4``, 2 };

// Size of the array

**int** n = arr.length;

// Function call

countSubarrays(arr, n);

}

}

Output:

2

#analysis #arrays #competitive programming #greedy #mathematical #subarray

Count subarrays having sum of elements at even and odd positions equal
8.80 GEEK