• + 0 comments

    O(n) proposal
    basically each element is visited ~twice

    def solve(arr):
        
        arr += [math.inf]
        A = [math.inf]
        s = 0
        
        i = 0
        while i < len(arr):
            
            if (e:= arr[i]) <= A[-1]:
                A.append(e)
                i += 1
                continue
            
            n = 0
            v = A[-1]
            while A[-1] == v:
                A.pop()
                n+=1
            s += math.perm(n, 2)
            
        return s