def newIndexIsLongerLength(oldStartIndex, oldEndIndex, newStartIndex, newEndIndex):
return (newEndIndex-newStartIndex) > (oldEndIndex-oldStartIndex)
def getMonotonicallyI(L):
startIndex = 0
endIndex = 0
for tmpStartIndex in range(len(L)-1):
tmpEndIndex = tmpStartIndex
while tmpEndIndex < len(L)-1:
if L[tmpEndIndex] > L[tmpEndIndex+1]:
break
tmpEndIndex += 1
if newIndexIsLongerLength(startIndex, endIndex, tmpStartIndex, tmpEndIndex):
startIndex, endIndex = tmpStartIndex, tmpEndIndex
return startIndex, endIndex
def getMonotonicallyD(L):
startIndex = len(L)-1
endIndex = len(L)-1
for tmpStartIndex in range(len(L)-1, 0, -1):
tmpEndIndex = tmpStartIndex
while tmpEndIndex > 0:
if L[tmpEndIndex] > L[tmpEndIndex-1]:
break
tmpEndIndex -= 1
if newIndexIsLongerLength(endIndex, startIndex, tmpEndIndex, tmpStartIndex):
startIndex, endIndex = tmpStartIndex, tmpEndIndex
#print(endIndex, startIndex)
return endIndex, startIndex
def longest_run(L):
"""
Assumes L is a list of integers containing at least 2 elements.
Finds the longest run of numbers in L, where the longest run can
either be monotonically increasing or monotonically decreasing.
In case of a tie for the longest run, choose the longest run
that occurs first.
Does not modify the list.
Returns the sum of the longest run.
"""
# Starting Values Of Index
startIndexI, endIndexI = getMonotonicallyI(L)
startIndexD, endIndexD = getMonotonicallyD(L)
if newIndexIsLongerLength(startIndexI, endIndexI, startIndexD, endIndexD):
return sum(L[startIndexD:endIndexD+1])
return sum(L[startIndexI:endIndexI+1])