Question:codility Lesson10 Flags
My Answer:
from math import sqrt
def solution(A):
lenA = len(A)
peakcnt = 0
nextpeak = [-1]*lenA
firstpeak = -1
for i in range(lenA - 2,0,-1):
if A[i] > A[i + 1] and A[i] > A[i - 1]:
nextpeak[i] = i
peakcnt += 1
firstpeak = i
else:
nextpeak[i] = nextpeak[i + 1]
if peakcnt < 2:
return peakcnt
#print nextpeak
maxflags = 0
maxflagnum = int(sqrt(lenA)) if peakcnt > int(sqrt(lenA)) else peakcnt
for i in range(maxflagnum + 1,1,-1):
flagsnum = 1
mayflag = i - 1
pos = firstpeak
while mayflag > 0:
#print pos,i
if pos + i >= lenA - 1:
break
pos = nextpeak[pos + i]
if pos == -1:
break
mayflag -= 1
flagsnum += 1
maxflags = max(maxflags,flagsnum)
return maxflags