Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Last Updated : 27 Dec, 2022
Improve Article
Save Article

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++

// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function to print and count the subarrays ranges
vector<pair<int, int> > countSubarrays(int arr[], int n)
{
    vector<pair<int, int> > p;
    // If the size is odd print -1
    if (n & 1) {
        cout << -1 << endl;
        return p;
    }

    // Initialize the count to 0
    int cnt = 0;

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

        // If consecutive elements are
        // of the same sign
        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;
}

// Driver function
int main()
{
    int arr[] = { -1, 1, 1, 1, 1, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);

    // Function call
    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

// Java code to implement the approach

import java.io.*;
import java.util.*;

class GFG {

  // Function to print and count the subarrays ranges
  static ArrayList<ArrayList<Integer> > countSubarrays(int arr[], int n)
  {
    ArrayList<ArrayList<Integer> > p
      = new ArrayList<ArrayList<Integer> >();
    // If the size is odd print -1
    if ((n & 1)!=0) {
      System.out.println(-1);
      return p;
    }

    // Initialize the count to 0
    int cnt = 0;

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

      // If consecutive elements are
      // of the same sign
      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;
  }

  // Driver function
  public static void main (String[] args) {
    int arr[] = { -1, 1, 1, 1, 1, 1 };
    int N = arr.length;

    // Function call
    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());
    }
  }
}

// This code is contributed by Pushpesh Raj

Python3

# Function to print and count the subarrays ranges
def countSubarrays(arr, n):
  p = []
  # If the size is odd print -1
  if (n & 1):
    print("-1")
    return p

  # Initialize the count to 0
  cnt = 0

  for i in range(0,n,2):
    
    # If consecutive elements are
    # of the same sign
    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


# Driver function
arr = [ -1, 1, 1, 1, 1, 1 ]
N = len(arr)

# Function call
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))
 # code by ksam24000

C#

// C# code to implement the approach

using System;
using System.Collections.Generic;

public class GFG {

  // Function to print and count the subarrays ranges
  static List<List<int> > countSubarrays(int[] arr, int n)
  {
    List<List<int> > p = new List<List<int> >();

    // If the size is odd print -1
    if ((n & 1) != 0) {
      Console.WriteLine(-1);
      return p;
    }

    // Initialize the count to 0
    int cnt = 0;

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

      // If consecutive elements are
      // of the same sign
      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()
  {

    // Code
    int[] arr = { -1, 1, 1, 1, 1, 1 };
    int N = arr.Length;

    // Function call
    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);
    }
  }
}

// This code is contributed by lokeshmvs21.

Javascript

        // JavaScript code to implement the approach

        // Function to print and count the subarrays ranges
        const countSubarrays = (arr, n) => {
            let p = [];
            // If the size is odd print -1
            if (n & 1) {
                console.log("-1<br/>");
                return p;
            }

            // Initialize the count to 0
            let cnt = 0;

            for (let i = 0; i < n; i += 2) {

                // If consecutive elements are
                // of the same sign
                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;
        }

        // Driver function

        let arr = [-1, 1, 1, 1, 1, 1];
        let N = arr.length;

        // Function call
        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);
        }

        // This code is contributed by rakeshsahni
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) 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!