找出数组的平衡下标

找出数组的平衡下标,平衡下标的左边的数组和 和 右边的数组和相等。

find the balance index of an array where balanced index i is defined as the one whose left sum is equal to the right sum of the index .

i.e summation (1 to i-1) = summation (i+1 to length of an array)

首先遍历一次数组找出数组的总和,

然后从0号位置开始,用sum减去0号位置的值,然后加到左边的和上,完成左边的和 和 剩余和的比较。

here first we traverse the array once to find total sum of array....

then we again start from 0th position and start subtracting value from total sum and go on adding it to leftsum and then compare leftsum and total remaining sum


#include <stdio.h>
int equil(int arr[],int size)
{
	int i = 0,arrsum = 0,leftsum = 0;
	for (i = 0;i<size;i++)
	{
		arrsum += arr[i];
	}
	for (i = 0;i<size;i++)
	{
		arrsum -= arr[i];
		if (leftsum == arrsum)
		{
			return i;
		}
		leftsum += arr[i];
	}
	return -1;
}


你可能感兴趣的:(找出数组的平衡下标)