Given an array containing N elements, each element is either 1 or 2. The task is to find out whether the array can be divided into 2 parts such that the sum of elements in both parts is equal.
Input : N = 3, arr[] = {1, 1, 2}
Output : YES
Input : N = 4, arr[] = {1, 2, 2, }
Output : NO
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
The idea is to observe that the array can be divided into two parts with equal sum only if the overall sum of the array is even, i.e. divisible by 2.
Let’s say the overall sum of the array is denoted by sum.
Now, there arise two cases:
- If sum/2 is even: When the value of sum/2 is also even, it means that the sum of each of the two parts is also even and we need not consider anything special. So, return true for this case.
- If sum/2 is odd: When the value of sum/2 is ODD, it means that the sum of each part is also odd. This is only possible when each of the two parts of the array contains at least one 1. Consider the cases when summing = 2 or 6 or 10. So, when sum/2 is odd, check if there is at least one 1 in the array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isSpiltPossible( int n, int a[])
{
int sum = 0, c1 = 0;
for ( int i = 0; i < n; i++) {
sum += a[i];
if (a[i] == 1) {
c1++;
}
}
if (sum % 2)
return false ;
if ((sum / 2) % 2 == 0)
return true ;
if (c1 > 0)
return true ;
else
return false ;
}
int main()
{
int n = 3;
int a[] = { 1, 1, 2 };
if (isSpiltPossible(n, a))
cout << "YES" ;
else
cout << "NO" ;
return 0;
}
|
Java
class GFG
{
static boolean isSpiltPossible( int n,
int a[])
{
int sum = 0 , c1 = 0 ;
for ( int i = 0 ; i < n; i++)
{
sum += a[i];
if (a[i] == 1 )
{
c1++;
}
}
if (sum % 2 != 0 )
return false ;
if ((sum / 2 ) % 2 == 0 )
return true ;
if (c1 > 0 )
return true ;
else
return false ;
}
public static void main(String[] args)
{
int n = 3 ;
int a[] = { 1 , 1 , 2 };
if (isSpiltPossible(n, a))
System.out.println( "YES" );
else
System.out.println( "NO" );
}
}
|
Python3
def isSpiltPossible(n, a):
Sum = 0
c1 = 0
for i in range (n):
Sum + = a[i]
if (a[i] = = 1 ):
c1 + = 1
if ( Sum % 2 ):
return False
if (( Sum / / 2 ) % 2 = = 0 ):
return True
if (c1 > 0 ):
return True
else :
return False
n = 3
a = [ 1 , 1 , 2 ]
if (isSpiltPossible(n, a)):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
class GFG
{
static bool isSpiltPossible( int n,
int [] a)
{
int sum = 0, c1 = 0;
for ( int i = 0; i < n; i++)
{
sum += a[i];
if (a[i] == 1)
{
c1++;
}
}
if (sum % 2 != 0)
return false ;
if ((sum / 2) % 2 == 0)
return true ;
if (c1 > 0)
return true ;
else
return false ;
}
public static void Main()
{
int n = 3;
int [] a = { 1, 1, 2 };
if (isSpiltPossible(n, a))
Console.WriteLine( "YES" );
else
Console.WriteLine( "NO" );
}
}
|
Javascript
<script>
function isSpiltPossible(n, a)
{
let sum = 0, c1 = 0;
for (let i = 0; i < n; i++)
{
sum += a[i];
if (a[i] == 1)
{
c1++;
}
}
if (sum % 2 != 0)
return false ;
if ((sum / 2) % 2 == 0)
return true ;
if (c1 > 0)
return true ;
else
return false ;
}
let n = 3;
let a = [ 1, 1, 2 ];
if (isSpiltPossible(n, a))
document.write( "YES" );
else
document.write( "NO" );
</script>
|
PHP
<?php
function isSpiltPossible( $n , $a )
{
$sum = 0; $c1 = 0;
for ( $i = 0; $i < $n ; $i ++)
{
$sum += $a [ $i ];
if ( $a [ $i ] == 1)
{
$c1 ++;
}
}
if ( $sum % 2 != 0)
return false;
if (( $sum / 2) % 2 == 0)
return true;
if ( $c1 > 0)
return true;
else
return false;
}
$n = 3;
$a = array ( 1, 1, 2 );
if (isSpiltPossible( $n , $a ))
echo ( "YES" );
else
echo ( "NO" );
?>
|
Time Complexity: O(N), since there runs a loop from 0 to (n – 1).
Auxiliary Space: O(1), since no extra space has been taken.
Approach 2: Dynamic Programming: Here is a dynamic programming approach to solve the problem of splitting an array into two parts with equal sum:
- Calculate the sum of all elements in the array.
- If the sum is odd, then it is not possible to split the array into two parts with equal sum. Return False.
- If the sum is even, then find if there exists a subset of the array whose sum is equal to half of the total sum. If such a subset exists, then the array can be split into two parts with equal sum. Otherwise, it is not possible. This can be done by dynamic programming to find such a subset using the following steps:
- Create a boolean 2D array dp[n+1][sum+1], where dp[i][j] represents whether it is possible to obtain a sum of j using the first i elements of the array.
- Initialize dp[0][0] to true, since it is always possible to obtain a sum of 0 using 0 elements.
- For each element a[i] in the array, iterate over all possible sums from 0 to sum/2, and update dp[i][j] as follows:
- If j < a[i], then dp[i][j] = dp[i-1][j], since we cannot include a[i] in the subset if it is greater than the current sum j. Otherwise, dp[i][j] = dp[i-1][j] || dp[i-1][j-a[i]], since we can either exclude or include a[i] in the subset.
- If dp[n][sum/2] is true, then it is possible to split the array into two parts with equal sum. Otherwise, it is not possible.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isSpiltPossible( int n, int a[])
{
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += a[i];
}
if (sum % 2 != 0) {
return false ;
}
int half_sum = sum / 2;
bool dp[n + 1][half_sum + 1];
for ( int i = 0; i <= n; i++) {
dp[i][0] = true ;
}
for ( int i = 1; i <= half_sum; i++) {
dp[0][i] = false ;
}
for ( int i = 1; i <= n; i++) {
for ( int j = 1; j <= half_sum; j++) {
if (j < a[i - 1]) {
dp[i][j] = dp[i - 1][j];
}
else {
dp[i][j] = dp[i - 1][j]
|| dp[i - 1][j - a[i - 1]];
}
}
}
return dp[n][half_sum];
}
int main()
{
int arr[] = { 1, 1, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
if (isSpiltPossible(N, arr)) {
cout << "YES" ;
}
else {
cout << "NO" ;
}
return 0;
}
|
Java
import java.util.*;
public class Main {
public static boolean isSplitPossible( int n, int [] a) {
int sum = 0 ;
for ( int i = 0 ; i < n; i++) {
sum += a[i];
}
if (sum % 2 != 0 ) {
return false ;
}
int half_sum = sum / 2 ;
boolean [][] dp = new boolean [n + 1 ][half_sum + 1 ];
for ( int i = 0 ; i <= n; i++) {
dp[i][ 0 ] = true ;
}
for ( int i = 1 ; i <= half_sum; i++) {
dp[ 0 ][i] = false ;
}
for ( int i = 1 ; i <= n; i++) {
for ( int j = 1 ; j <= half_sum; j++) {
if (j < a[i - 1 ]) {
dp[i][j] = dp[i - 1 ][j];
} else {
dp[i][j] = dp[i - 1 ][j] || dp[i - 1 ][j - a[i - 1 ]];
}
}
}
return dp[n][half_sum];
}
public static void main(String[] args) {
int [] arr = { 1 , 1 , 2 };
int N = arr.length;
if (isSplitPossible(N, arr)) {
System.out.println( "YES" );
} else {
System.out.println( "NO" );
}
}
}
|
Python3
def isSpiltPossible(n, a):
sum = 0
for i in range (n):
sum + = a[i]
if sum % 2 ! = 0 :
return False
half_sum = sum / / 2
dp = [[ False for j in range (half_sum + 1 )] for i in range (n + 1 )]
for i in range (n + 1 ):
dp[i][ 0 ] = True
for i in range ( 1 , half_sum + 1 ):
dp[ 0 ][i] = False
for i in range ( 1 , n + 1 ):
for j in range ( 1 , half_sum + 1 ):
if j < a[i - 1 ]:
dp[i][j] = dp[i - 1 ][j]
else :
dp[i][j] = dp[i - 1 ][j] or dp[i - 1 ][j - a[i - 1 ]]
return dp[n][half_sum]
arr = [ 1 , 1 , 2 ]
N = len (arr)
if isSpiltPossible(N, arr):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
public class SplitArray
{
public static bool IsSplitPossible( int n, int [] arr)
{
int sum = 0;
for ( int i = 0; i < n; i++)
{
sum += arr[i];
}
if (sum % 2 != 0)
{
return false ;
}
int halfSum = sum / 2;
bool [,] dp = new bool [n + 1, halfSum + 1];
for ( int i = 0; i <= n; i++)
{
dp[i, 0] = true ;
}
for ( int i = 1; i <= halfSum; i++)
{
dp[0, i] = false ;
}
for ( int i = 1; i <= n; i++)
{
for ( int j = 1; j <= halfSum; j++)
{
if (j < arr[i - 1])
{
dp[i, j] = dp[i - 1, j];
}
else
{
dp[i, j] = dp[i - 1, j] || dp[i - 1, j - arr[i - 1]];
}
}
}
return dp[n, halfSum];
}
public static void Main( string [] args)
{
int [] arr = { 1, 1, 2 };
int n = arr.Length;
if (IsSplitPossible(n, arr))
{
Console.WriteLine( "YES" );
}
else
{
Console.WriteLine( "NO" );
}
}
}
|
Javascript
function isSplitPossible(n, a) {
let sum = 0;
for (let i = 0; i < n; i++) {
sum += a[i];
}
if (sum % 2 !== 0) {
return false ;
}
const halfSum = sum / 2;
const dp = Array.from({
length: n + 1
}, () => Array(halfSum + 1));
for (let i = 0; i <= n; i++) {
dp[i][0] = true ;
}
for (let i = 1; i <= halfSum; i++) {
dp[0][i] = false ;
}
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= halfSum; j++) {
if (j < a[i - 1]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - a[i - 1]];
}
}
}
return dp[n][halfSum];
}
const arr = [1, 1, 2];
const N = arr.length;
if (isSplitPossible(N, arr)) {
console.log( "YES" );
} else {
console.log( "NO" );
}
|
Time Complexity: O(n*sum), where n is the size of the array and sum is the sum of all elements in the array.
Space complexity: O(sum/2)