# How to optimally divide an array into two subarrays so that sum of elements in both are same ?

Answer : Given an array of integers greater than zero…

## How to optimally divide an array into two subarrays so that sum of elements in both are same ?

There are two methods used to split arrays,

• Given an array of integers greater than zero, find if it is possible to split it in two subarrays (without reordering the elements), such that the sum of the two subarrays is the same. For example,
• Given an array of integers, find if it’s possible to remove exactly one integer from the array that divides the array into two subarrays with the same sum. For Example,
• On removing element 2 at index 1, the array gets divided into two subarrays  and [3, 2, 1] having equal sum.

## Sample Code in Java

``````/ Java program to split an array
// into two equal sum subarrays
import java.io.*;

class Wikitechy {

// Returns split point. If
// not possible, then return -1.
static int findSplitPoint(int arr[], int n) {

int leftSum = 0;

// traverse array element
for (int i = 0; i < n; i++) {
// add current element to left Sum
leftSum += arr[i];

// find sum of rest array
// elements (rightSum)
int rightSum = 0;

for (int j = i + 1; j < n; j++)
rightSum += arr[j];

// split point index
if (leftSum == rightSum)
return i + 1;
}

// if it is not possible to
// split array into two parts
return -1;
}

// Prints two parts after finding
// split point using findSplitPoint()
static void printTwoParts(int arr[], int n) {

int splitPoint = findSplitPoint(arr, n);

if (splitPoint == -1 || splitPoint == n) {
System.out.println("Not Possible");
return;
}

for (int i = 0; i < n; i++) {
if (splitPoint == i)
System.out.println();

System.out.print(arr[i] + " ");

}
}

// Driver program

public static void main(String[] args) {

int arr[] = {1,1,0,2};
int n = arr.length;
printTwoParts(arr, n);

}
}``````

## What is Linear Sort in Java ?

Answer : One of the simplest Sorting techniques is a linear sort…

## Java program to find second largest number in an array ?

Answer : Given an array of integers, our task is to write a program…

## What is the purpose of method overriding in java where we are completely re-defining a inherited method ?

Answer : Exception in Java represents that problem arises during the execution of the program…

## How to check if two rectangles intersect or not ?

Answer : The following standard Java coding practices to solve…

## How to check if a string contains the sequences of characters or not using java ?

Answer : java.lang.String.contains() method searches the sequence of characters…

## Difference between JDK JRE and JVM ?

Answer : Java Development Kit is the core component…