You are given an array A consisting of the integers −1, 0 and 1. A slice of that array is any pair of integers (P, Q) such that 0 ≤ P ≤ Q < N. Your task is to find the longest slice of A whose elements yield a non-negative sum.
Write a function:
def solution(A)
that, given an array A of length N, consisting only of the values −1, 0, 1, returns the length of the longest slice of A that yields a non-negative sum. If there's no such slice, your function should return 0.
For example, given A = [−1, −1, 1, −1, 1, 0, 1, −1, −1], your function should return 7, as the slice starting at the second position and ending at the eighth is the longest slice with a non-negative sum.
For another example, given A = [1, 1, −1, −1, −1, −1, −1, 1, 1] your function should return 4: both the first four elements and the last four elements of array A are longest valid slices.
Write an efficient algorithm for the following assumptions:
- N is an integer within the range [2..100,000];
- each element of array A is an integer within the range [−1..1].
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# Solved using Algorithm provied in the paper Optimal algorithms for locating the longest and shortest segments satisfying a sum or an average constraint
if sum(A)==-len(A):
return 0
M = [0]*(len(A)+1)
CumSum = [0]*(len(A)+1)
initial = 0
final = 0
for i in range(1, (len(A)+1)):
CumSum[i] = CumSum[i-1] + A[i-1]
if (CumSum[i-1]<CumSum[M[i-1]]):
M[i]=i-1
else:
M[i] = M[i -1]
k=i-final+initial- 1;
while k >0 :
if (CumSum[i] -CumSum[M[k]]) >= 0:
k= M[k]
else:
break
initial= k +1
final= i
return final-initial+1
pass
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# Solved using Algorithm provied in the paper Optimal algorithms for locating the longest and shortest segments satisfying a sum or an average constraint
if sum(A)==-len(A):
return 0
M = [0]*(len(A)+1)
CumSum = [0]*(len(A)+1)
initial = 0
final = 0
for i in range(1, (len(A)+1)):
CumSum[i] = CumSum[i-1] + A[i-1]
if (CumSum[i-1]<CumSum[M[i-1]]):
M[i]=i-1
else:
M[i] = M[i -1]
k=i-final+initial- 1;
while k >0 :
if (CumSum[i] -CumSum[M[k]]) >= 0:
k= M[k]
else:
break
initial= k +1
final= i
return final-initial+1
pass
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# Solved using Algorithm provied in the paper Optimal algorithms for locating the longest and shortest segments satisfying a sum or an average constraint
if sum(A)==-len(A):
return 0
M = [0]*(len(A)+1)
CumSum = [0]*(len(A)+1)
initial = 0
final = 0
for i in range(1, (len(A)+1)):
CumSum[i] = CumSum[i-1] + A[i-1]
if (CumSum[i-1]<CumSum[M[i-1]]):
M[i]=i-1
else:
M[i] = M[i -1]
k=i-final+initial- 1;
while k >0 :
if (CumSum[i] -CumSum[M[k]]) >= 0:
k= M[k]
else:
break
initial= k +1
final= i
return final-initial+1
pass
The solution obtained perfect score.