I think below solution works and it is O(n)
Idea:
- First find the min element less than 0, by summing up all elements
- Now count the negative elements from beginning to make min value to zero or greater
Solution:
def min_relocations(A):
prev = 0
min_ele = math.inf
for ele in A:
prev = ele+prev
min_ele = min(min_ele,prev)
if(min_ele>=0):
return 0
count = 0
for ele in A:
if(ele<0):
min_ele = min_ele-ele
count+=1
if(min_ele>=0):
return count
print(min_relocations([10,-10,-1,-1,10])) -- 1
print(min_relocations([-1,-1,-1,1,1,1,1])) -- 3
print(min_relocations([5,-2,-3,1])) -- 0