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:
C++
#include <bits/stdc++.h>
using namespace std;
vector<pair< int , int > > countSubarrays( int arr[], int n)
{
vector<pair< int , int > > p;
if (n & 1) {
cout << -1 << endl;
return p;
}
int cnt = 0;
for ( int i = 0; i < n; i += 2) {
if ((arr[i] > 0 && arr[i + 1] > 0)
|| (arr[i] < 0 && arr[i + 1] < 0)) {
p.push_back({ i, i + 1 });
cnt++;
}
else {
p.push_back({ i, i });
p.push_back({ i + 1, i + 1 });
cnt += 2;
}
}
return p;
}
int main()
{
int arr[] = { -1, 1, 1, 1, 1, 1 };
int N = sizeof (arr) / sizeof (arr[0]);
vector<pair< int , int > > ans = countSubarrays(arr, N);
if (ans.size() == 0)
cout << "-1\n" ;
else {
for ( auto u : ans) {
cout << u.first << " " << u.second << "\n" ;
}
cout << ans.size();
}
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static ArrayList<ArrayList<Integer> > countSubarrays( int arr[], int n)
{
ArrayList<ArrayList<Integer> > p
= new ArrayList<ArrayList<Integer> >();
if ((n & 1 )!= 0 ) {
System.out.println(- 1 );
return p;
}
int cnt = 0 ;
for ( int i = 0 ; i < n; i += 2 ) {
if ((arr[i] > 0 && arr[i + 1 ] > 0 )
|| (arr[i] < 0 && arr[i + 1 ] < 0 )) {
p.add( new ArrayList<Integer>(Arrays.asList(i, i+ 1 )));
cnt++;
}
else {
p.add( new ArrayList<Integer>(Arrays.asList(i, i)));
p.add( new ArrayList<Integer>(Arrays.asList(i+ 1 , i+ 1 )));
cnt += 2 ;
}
}
return p;
}
public static void main (String[] args) {
int arr[] = { - 1 , 1 , 1 , 1 , 1 , 1 };
int N = arr.length;
ArrayList<ArrayList<Integer> > ans= countSubarrays(arr, N);
if (ans.size() == 0 )
System.out.println( "-1" );
else {
for (ArrayList<Integer> u : ans) {
System.out.println(u.get( 0 )+ " " +u.get( 1 ));
}
System.out.print(ans.size());
}
}
}
|
Python3
def countSubarrays(arr, n):
p = []
if (n & 1 ):
print ( "-1" )
return p
cnt = 0
for i in range ( 0 ,n, 2 ):
if ((arr[i] > 0 and arr[i + 1 ] > 0 ) or (arr[i] < 0 and arr[i + 1 ] < 0 )):
p.append([ i, i + 1 ])
cnt + = 1
else :
p.append([ i, i ])
p.append([ i + 1 , i + 1 ])
cnt + = 2
return p
arr = [ - 1 , 1 , 1 , 1 , 1 , 1 ]
N = len (arr)
ans = countSubarrays(arr, N)
if ( len (ans) = = 0 ):
print ( "-1" )
else :
for i in range ( 0 , len (ans)):
print (ans[i][ 0 ] , " " , ans[i][ 1 ])
print ( len (ans))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static List<List< int > > countSubarrays( int [] arr, int n)
{
List<List< int > > p = new List<List< int > >();
if ((n & 1) != 0) {
Console.WriteLine(-1);
return p;
}
int cnt = 0;
for ( int i = 0; i < n; i += 2) {
if ((arr[i] > 0 && arr[i + 1] > 0)
|| (arr[i] < 0 && arr[i + 1] < 0)) {
p.Add( new List< int >{ i, i + 1 });
cnt++;
}
else {
p.Add( new List< int >{ i, i });
p.Add( new List< int >{ i + 1, i + 1 });
cnt += 2;
}
}
return p;
}
static public void Main()
{
int [] arr = { -1, 1, 1, 1, 1, 1 };
int N = arr.Length;
List<List< int > > ans = countSubarrays(arr, N);
if (ans.Count == 0)
Console.WriteLine( "-1" );
else {
foreach ( var u in ans)
{
Console.WriteLine(u[0] + " " + u[1]);
}
Console.Write(ans.Count);
}
}
}
|
Javascript
const countSubarrays = (arr, n) => {
let p = [];
if (n & 1) {
console.log( "-1<br/>" );
return p;
}
let cnt = 0;
for (let i = 0; i < n; i += 2) {
if ((arr[i] > 0 && arr[i + 1] > 0)
|| (arr[i] < 0 && arr[i + 1] < 0)) {
p.push([i, i + 1]);
cnt++;
}
else {
p.push([i, i]);
p.push([i + 1, i + 1]);
cnt += 2;
}
}
return p;
}
let arr = [-1, 1, 1, 1, 1, 1];
let N = arr.length;
let ans = countSubarrays(arr, N);
if (ans.length == 0)
console.log( "-1<br/>" );
else {
for (let u in ans) {
console.log(`${ans[u][0]} ${ans[u][1]}<br/>`);
}
console.log(ans.length);
}
|
Time Complexity: O(N) where N is the size of the array
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...