 1599152400

# Split an Array to maximize subarrays having equal count of odd and even elements

Given an array arr[] of size N and an integer K, the task is to split the given array into maximum possible subarrays having equal count of even and odd elements such that the cost to split the array does not exceed K.

The cost to split an array into a subarray is the difference between the last and first elements of the subarrays respectively.

Examples:

Input:_ arr[] = {1, 2, 5, 10, 15, 20}, K = 4_

Output:_ 1_

Explanation:

The optimal way is to split the array between 2 and 5.

So it splits into {1, 2} and {5, 10, 15, 20}.

Also, both the subarrays contain an equal number of even and odd elements. The cost of the split is abs(2 – 5) = 3 which is ≤ K.

Input:_ arr[] = {1, 2, 3, 4, 5, 6}, K = 100_

Output:_ 2_

Explanation:

The optimal way is to make two splits such that the subarrays formed are {1, 2}, {3, 4}, {5, 6}.

The total cost is abs(2 – 3) + abs(4 – 5) = 2

### Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The simplest approach to solve this problem is as follows:

1. Split the array at every index and check if the cost is less than K or not.
2. If the cost is less than K, then check if the number of odd and even elements in the subarray are equal or not.
3. Now check if another split is possible or not by repeating the same steps.
4. After checking all possible splits, print the minimum cost which add up to a sum less than K.

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

Efficient Approach: The idea is to maintain the counters which store the number of even numbers and odd numbers in the array. Below are the steps:

1. Initialize an array (say poss[]) which stores the cost of all possible splits.
2. Traverse through the array arr[]. For every index, check if the subarray up to this index and the subarray starting from the next index has equal count of odd and even elements.
3. If the above condition satisfies, then a split is possible. Store the cost associated with this split in poss[].
4. Repeat the above steps for all the elements in the array and store the costs of every split.
5. Cost of split at index i can be obtained by abs(arr[i + 1] – arr[i]).
6. Now, in order to find the maximum number of possible splits, sort the array poss[] that contains the costs of each possible split.
7. Now select all minimum costs from poss[] whose sum is less than or equal to K.

Below is the implementation of the above approach:

• C++

`// C++ program for the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function to find the cost of`

`// splitting the arrays into subarray`

`// with cost less than K`

`**int**` `make_cuts(``**int**` `arr[],` `**int**` `n,` `**int**` `K)`

`{`

`// Store the possible splits`

`**int**` `ans = 0;`

`// Stores the cost of each split`

`vector<``**int**``> poss;`

`// Stores the count of even numbers`

`**int**` `ce = 0;`

`// Stores the count`

`// of odd numbers`

`**int**` `co = 0;`

`**for**` `(``**int**` `x = 0; x < n - 1; x++) {`

`// Count of odd & even elements`

`**if**` `(arr[x] % 2 == 0)`

`ce++;`

`**else**`

`co++;`

`// Check the required conditions`

`// for a valid split`

`**if**` `(ce == co && co > 0`

`&& ce > 0) {`

`poss.push_back(`

`**abs**``(arr[x]`

`- arr[x + 1]));`

`}`

`}`

`// Sort the cost of splits`

`sort(poss.begin(), poss.end());`

`// Find the minimum split costs`

`// adding up to sum less than K`

`**for**` `(``**int**` `x : poss) {`

`**if**` `(K >= x) {`

`ans++;`

`K -= x;`

`}`

`**else**`

`**break**``;`

`}`

`**return**` `ans;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`// Given array and K`

`**int**` `N = 6;`

`**int**` `K = 4;`

`**int**` `arr[] = { 1, 2, 5, 10, 15, 20 };`

`// Function Call`

`cout << make_cuts(arr, N, K);`

`}`

Output:

``````1
``````

Time Complexity:_ O(N log(N))_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #hash #sorting #frequency-counting #subarray

## Buddha Community  1599152400

## Split an Array to maximize subarrays having equal count of odd and even elements

Given an array arr[] of size N and an integer K, the task is to split the given array into maximum possible subarrays having equal count of even and odd elements such that the cost to split the array does not exceed K.

The cost to split an array into a subarray is the difference between the last and first elements of the subarrays respectively.

Examples:

Input:_ arr[] = {1, 2, 5, 10, 15, 20}, K = 4_

Output:_ 1_

Explanation:

The optimal way is to split the array between 2 and 5.

So it splits into {1, 2} and {5, 10, 15, 20}.

Also, both the subarrays contain an equal number of even and odd elements. The cost of the split is abs(2 – 5) = 3 which is ≤ K.

Input:_ arr[] = {1, 2, 3, 4, 5, 6}, K = 100_

Output:_ 2_

Explanation:

The optimal way is to make two splits such that the subarrays formed are {1, 2}, {3, 4}, {5, 6}.

The total cost is abs(2 – 3) + abs(4 – 5) = 2

### Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The simplest approach to solve this problem is as follows:

1. Split the array at every index and check if the cost is less than K or not.
2. If the cost is less than K, then check if the number of odd and even elements in the subarray are equal or not.
3. Now check if another split is possible or not by repeating the same steps.
4. After checking all possible splits, print the minimum cost which add up to a sum less than K.

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

Efficient Approach: The idea is to maintain the counters which store the number of even numbers and odd numbers in the array. Below are the steps:

1. Initialize an array (say poss[]) which stores the cost of all possible splits.
2. Traverse through the array arr[]. For every index, check if the subarray up to this index and the subarray starting from the next index has equal count of odd and even elements.
3. If the above condition satisfies, then a split is possible. Store the cost associated with this split in poss[].
4. Repeat the above steps for all the elements in the array and store the costs of every split.
5. Cost of split at index i can be obtained by abs(arr[i + 1] – arr[i]).
6. Now, in order to find the maximum number of possible splits, sort the array poss[] that contains the costs of each possible split.
7. Now select all minimum costs from poss[] whose sum is less than or equal to K.

Below is the implementation of the above approach:

• C++

`// C++ program for the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function to find the cost of`

`// splitting the arrays into subarray`

`// with cost less than K`

`**int**` `make_cuts(``**int**` `arr[],` `**int**` `n,` `**int**` `K)`

`{`

`// Store the possible splits`

`**int**` `ans = 0;`

`// Stores the cost of each split`

`vector<``**int**``> poss;`

`// Stores the count of even numbers`

`**int**` `ce = 0;`

`// Stores the count`

`// of odd numbers`

`**int**` `co = 0;`

`**for**` `(``**int**` `x = 0; x < n - 1; x++) {`

`// Count of odd & even elements`

`**if**` `(arr[x] % 2 == 0)`

`ce++;`

`**else**`

`co++;`

`// Check the required conditions`

`// for a valid split`

`**if**` `(ce == co && co > 0`

`&& ce > 0) {`

`poss.push_back(`

`**abs**``(arr[x]`

`- arr[x + 1]));`

`}`

`}`

`// Sort the cost of splits`

`sort(poss.begin(), poss.end());`

`// Find the minimum split costs`

`// adding up to sum less than K`

`**for**` `(``**int**` `x : poss) {`

`**if**` `(K >= x) {`

`ans++;`

`K -= x;`

`}`

`**else**`

`**break**``;`

`}`

`**return**` `ans;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`// Given array and K`

`**int**` `N = 6;`

`**int**` `K = 4;`

`**int**` `arr[] = { 1, 2, 5, 10, 15, 20 };`

`// Function Call`

`cout << make_cuts(arr, N, K);`

`}`

Output:

``````1
``````

Time Complexity:_ O(N log(N))_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #hash #sorting #frequency-counting #subarray 1595510040

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

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 1594238700

## Find array elements equal to sum of any subarray of at least size 2

Given an array arr[], the task is to find the elements from the array which are equal to the sum of any sub-array of size greater than 1.

Examples:

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

Output:_ 3, 5, 6_

Explanation:

The elements 3, 5, 6 are equal to sum of subarrays {1, 2},{2, 3} and {1, 2, 3} respectively.

Input:_ arr[] = {5, 6, 10, 1, 3, 4, 8, 16}_

Output:_ 4, 8, 16_

Explanation:

The elements 4, 8, 16 are equal to the sum of subarrays {1, 3}, {1, 3, 4}, {1, 3, 4, 8} respectively

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to use prefix sum array to solve the given problem. Create a prefix[] array that stores the prefix sum of all its preceding elements for every index. Store the sum of all subarrays in a map and search if any array element is present in the map or not.

#arrays #hash #prefix-sum #subarray #subarray-sum 1594285500

## Find array elements equal to sum of any subarray of at least size 2

Given an array arr[], the task is to find the elements from the array which are equal to the sum of any sub-array of size greater than 1.

Examples:

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

Output:_ 3, 5, 6_

Explanation:

The elements 3, 5, 6 are equal to sum of subarrays {1, 2},{2, 3} and {1, 2, 3} respectively.

Input:_ arr[] = {5, 6, 10, 1, 3, 4, 8, 16}_

Output:_ 4, 8, 16_

Explanation:

The elements 4, 8, 16 are equal to the sum of subarrays {1, 3}, {1, 3, 4}, {1, 3, 4, 8} respectively

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to use prefix sum array to solve the given problem. Create a prefix[] array that stores the prefix sum of all its preceding elements for every index. Store the sum of all subarrays in a map and search if any array element is present in the map or not.

#arrays #hash #prefix-sum #subarray #subarray-sum 1597935600

## Count of subarrays having sum equal to its length

Given an array** arr[]** of size N, the task is to find the number of subarrays having the sum of its elements equal to the number of elements in it.

Examples:

Input: N = 3, arr[] = {1, 0, 2}

Output:_ 3_

Explanation:

Total number of subarrays are 6 i.e., {1}, {0}, {2}, {1, 0}, {0, 2}, {1, 0, 2}.

_Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., _

1) {1}, sum = 1, length = 1.

2) {0, 2}, sum = 2, length = 2.

3) {1, 0, 2}, sum = 3, length = 3.

Input:_ N = 3, arr[] = {1, 1, 0}_

Output:_ 3_

Explanation:

Total number of subarrays are 6 i.e. {1}, {1}, {0}, {1, 1}, {1, 0}, {1, 1, 0}.

_Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., _

1) {1}, sum = 1, length = 1.

2) {1}, sum = 1, length = 1.

3) {1, 1}, sum = 2, length = 2.

Naive Approach: The idea is to generate all the subarrays of the array and if the sum of elements of the subarray is equal to the number of elements in it then count this subarray. Print the count after checking all the subarrays.

_Time Complexity: _O(N2)

Auxiliary Space:_ O(N)_

**Efficient Approach: **This problem can be converted into a simpler problem by using observation. If all the elements of the array are decremented by 1, then all the subarrays of array arr[] with a sum equal to its number of elements are same as finding the number of subarrays with sum 0 in the new array(formed by decrementing all the elements of arr[ ] by 1). Below are the steps:

1. Decrement all the array elements by 1.
2. Initialize a prefix array with prefix = arr.
3. Traverse the given array arr[] from left to right, starting from index 1 and update a prefix sum array as pref[i] = pref[i-1] + arr[i].
4. Initialize the answer to 0.
5. Iterate the prefix array pref[] from left to right and increment the answer by the value of the current element in the map.
6. Increment the value of the current element in the map.
7. Print the value of answer after the above steps.

Below is the implementation of the above approach:

• C++
• Python3

`// C++ program for the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function that counts the subarrays`

`// with sum of its elements as its length`

`**int**` `countOfSubarray(``**int**` `arr[],` `**int**` `N)`

`{`

`// Decrementing all the elements`

`// of the array by 1`

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

`arr[i]--;`

`// Making prefix sum array`

`**int**` `pref[N];`

`pref = arr;`

`**for**` `(``**int**` `i = 1; i < N; i++)`

`pref[i] = pref[i - 1] + arr[i];`

`// Declare map to store count of`

`// elements upto current element`

`map<``**int**``,` `**int**``> mp;`

`**int**` `answer = 0;`

`// To count all the subarrays`

`// whose prefix sum is 0`

`mp++;`

`// Iterate the array`

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

`// Increment answer by count of`

`// current element of prefix array`

`answer += mp[pref[i]];`

`mp[pref[i]]++;`

`}`

`// Return the answer`

`**return**` `answer;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`// Given array arr[]`

`**int**` `arr[] = { 1, 1, 0 };`

`**int**` `N =` `**sizeof**` `arr /` `**sizeof**` `arr;`

`// Function call`

`cout << countOfSubarray(arr, N);`

`**return**` `0;`

`}`

Output:

``````3
``````

Time Complexity:_ O(N * Log(N))_

Auxiliary Space:_ O(N)_

#arrays #competitive programming #dynamic programming #greedy #mathematical #cpp-map #subarray #subarray-sum