Solve almostIncreasingSequence (Codefights)

后端 未结 15 1257
谎友^
谎友^ 2020-12-08 07:35

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

15条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 08:00

    With Python3, I started with something like this...

    def almostIncreasingSequence(sequence):
        for i, x in enumerate(sequence):
            ret = False
            s = sequence[:i]+sequence[i+1:]
            for j, y in enumerate(s[1:]):
                if s[j+1] <= s[j]:
                    ret = True
                    break
                if ret:
                    break
            if not ret:
                return True
        return False
    

    But kept timing out on Check #29.

    I kicked myself when I realized that this works, too, but still times out on #29. I have no idea how to speed it up.

    def almostIncreasingSequence(sequence):
        for i, x in enumerate(sequence):    
            s = sequence[:i]
            s.extend(sequence[i+1:])
            if s == sorted(set(s)):
                return True
        return False
    

提交回复
热议问题