VOOZH about

URL: https://www.geeksforgeeks.org/dsa/split-array-into-maximum-subarrays-so-that-sum-of-alternating-sums-is-0/

⇱ Split Array into maximum Subarrays so that sum of alternating sums is 0 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Split Array into maximum Subarrays so that sum of alternating sums is 0

Last Updated : 27 Dec, 2022

Given an array arr[] of 1s and -1s, the task is to partition the array into maximum subarrays such that the sum of the alternating sum of all the subarrays is 0. Print the ranges of the subarrays and the number of subarrays. 

Note: The alternating sum of a subarray a[] is defined as a[0] - a[1] + a[2] - a[3] . . .

Examples:
Input: {-1, 1, 1, 1, 1, 1}
Output: 
{0, 0}, {1, 1}, {2, 3}, {4, 5}
4
Explanation: From index 0 to 0 the alternating sum is -1. From 1 to 1 the alternating sum is 1. From index 2 to 3 and index 4 to 5 the sum is 1 - 1 = 0. The sum of the alternating sums is -1 + 1 + 0 + 0 = 0. So these are two partitions whose sum of alternating sums is 0.

Input: {1, 1, 1, 1}
Output:
{0, 1}, {2, 3}
2

Approach: This problem can be solved using the following idea.

Since the only elements present in the array are 1 and -1 for any two consecutive elements there are 4 possibilities in total  like {1, 1}, {1, -1}, {-1, 1}, {-1, -1} the alternating sum in the 4 cases is :

{1, 1} -> 1 - 1 = 0;
{1, -1}-> 1 + 1 = 2;  ---> In this case it can be considered as {1}, {-1} => 0
{-1, 1}-> -1 - 1 = -2; ---> In this case it can be considered as {-1}, {1} => 0
{-1, -1}-> -1 + 1 = 0;

In the first and fourth case the alternating sum is 0 so in that case they can be considered as one subarray and in remaining two cases individual element is considered as a subarray.

Follow the steps mentioned below to solve the problem:

  • Check if the size of the array is odd if the size is odd it is not possible to have 0 sum of alternating sums so print -1.
  • Now traverse through the array and check every two adjacent if they have the same sign then consider both as a subarray else consider both as different subarrays.
    • If the signs are the same, the subarray is of the range {i, i+1} and increment count by 1
    • Else the subarrays are {i, i} and {i, i+1} and increment count by 2
  • Finally, print the subarrays and count of subarrays.

Below is the implementation of the above approach:


Output
0 0
1 1
2 3
4 5
4

Time Complexity: O(N) where N is the size of the array
Space Complexity: O(1) 

Comment