Problem Statement:
Given a sequence of integers as an array, we have to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
Example
For sequence = [1, 3, 2, 1], the output should be almostIncreasingSequence(sequence) = false;
Since there is no one element in this array that can be removed in order to get a strictly increasing sequence.
For sequence = [1, 3, 2], the output should be almostIncreasingSequence(sequence) = true.
You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].
I have formulated a solution for this which is as follows:
def almostIncreasingSequence(sequence):
j=0
k=0
i=1
m=1
jflag=0
kflag=0
dupsequence = list(sequence)
while i < len(sequence):
difference = sequence[i]-sequence[i-1]
if (difference) <= 0:
j = j+1
del sequence[i]
i = 0
if j > 1:
jflag = 1
break
i = i + 1
while m < len(dupsequence):
if (dupsequence[m]-dupsequence[m-1]) <= 0:
k = k+1
del dupsequence[m-1]
m = 0
if k > 1:
kflag = 1
break
m = m + 1
if kflag == 0 or jflag == 0:
return True
if jflag ==1 and kflag==1:
return False
It is working and when I try to run the above code on the stress tests provided in this link, especially the test: 26 is taking 167 milliseconds.
I tried to profile using this piece of code:
def timex():
return time()*1000
def main():
starttime = timex()
almostIncreasingSequence(sequence)
endtime = timex()
print 'timetaken to execute is %d milliseconds' %(endtime-starttime)
if __name__ == '__main__':
main()
timetaken to execute is 167 milliseconds
I'm asking for a more performance and resource efficient implementation. I'm also an amateur in Python.