Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
O(n) (using partial sums) solution in Speedy category for Can Balance by David_Jones
def can_balance(weights):
n = len(weights)
partial_sums = [0] * n
for i in range(n):
partial_sums[i] = partial_sums[i-1] + weights[i]
left, right = 0, sum(i*weights[i] for i in range(n))
for i in range(n):
if left > right:
return -1
if left == right:
return i
left += partial_sums[i]
right += partial_sums[i] - partial_sums[-1]
May 22, 2019
Comments: