Python canbalance Given a nonempty array return true if ther
Python can_balance
Given a non-empty array, return true if there is a place to split the array so that the sum of the numbers on one side is equal to the sum of the numbers on the other side.
can_balance([1, 1, 1, 2, 1]) True
can_balance([2, 1, 1, 2, 1]) False
can_balance([10, 10]) True
def can_balance(nums):
| Given a non-empty array, return true if there is a place to split the array so that the sum of the numbers on one side is equal to the sum of the numbers on the other side.
def can_balance(nums): |
Solution
public class CanBalance
{
public static void main (String args[])
{
int arr[] = {4, 5, 8, 1, 3, 9, 7, 11, 100, 75, 84, 65};
int set1[] = new int[(1+arr.length)/2];
int set2[] = new int[(1+arr.length)/2];
int set1sum ;
int set2sum ;
divideInArrayEqualSums (arr, set1, set2);
}
private static void divideInArrayEqualSums(int[] arr, int[] set1, int[] set2)
{
int setSize = set1.length;
Arrays.sort(arr);
int pos1=0;
int pos2=0;
int i=arr.length-1;
int sum1 = 0;
int sum2 = 0;
while (pos1 < setSize && pos2 < setSize)
{
if (sum1 < sum2)
{
set1[pos1] = arr[i];
pos1++;
sum1 += arr[i];
}
else
{
set2[pos2] = arr[i];
pos2++;
sum2 += arr[i];
}
i--;
}
while (i>=0)
{
if (pos1 < setSize)
set1[pos1++] = arr[i];
else
set2[pos2++] = arr[i];
i--;
}
printArrayWithSum(arr);
printArrayWithSum1(set1);
printArrayWithSum2(set2);
}
static void printArrayWithSum (int arr[])
{
int sum = 0;
for (int i=0; i<arr.length; i++)
{
sum1 += arr[i];
System.out.print(arr[i]+\",\");
}
System.out.println(\" = \" + sum);
}
static void printArrayWithSum1 (int arr[])
{
int sum1 = 0;
for (int i=0; i<arr.length; i++)
{
sum1 += arr[i];
System.out.print(arr[i]+\",\");
}
int set1Sum = sum1;
System.out.println(\" = \" + sum1);
}
static void printArrayWithSum2 (int arr[])
{
int sum2 = 0;
for (int i=0; i<arr.length; i++)
{
sum2 += arr[i];
System.out.print(arr[i]+\",\");
}
int set1Sum2 = sum2;
System.out.println(\" = \" + sum2);
}
if(set1Sum == set2Sum){
return True
}
else {
return False
}
}

