代码拉取完成,页面将自动刷新
Array Equilibrium Index
Send Feedback
Find and return the equilibrium index of an array. Equilibrium index of an array is an index i such that the sum of elements at indices less than i is equal to the sum of elements at indices greater than i.
Element at index i is not included in either part.
If more than one equilibrium index is present, you need to return the first one. And return -1 if no equilibrium index is present.
Input format :
Line 1 : Size of input array
Line 2 : Array elements (separated by space)
Constraints:
Time Limit: 1 second
Size of input array lies in the range: [1, 1000000]
Sample Input :
7
-7 1 5 2 -4 3 0
Sample Output :
3
def equilibrium(arr):
# finding the sum of whole array
total_sum = sum(arr)
leftsum = 0
for i, num in enumerate(arr):
# total_sum is now right sum
# for index i
total_sum -= num
if leftsum == total_sum:
return i
leftsum += num
# If no equilibrium index found,
# then return -1
return -1
n = int(input())
arr = [int(i) for i in input().strip().split()]
print(equilibrium(arr))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。