Source Code
n = int(input())
a = [*map(int, input().split())]
ans = []
if any(i < 0 for i in a):
    t = sum(i for i in a if i < 0)
    b = [i for i in a if(i > 0)]
    o = min(b)
    ind = 0
    oo = len(b)
    while ind < oo - 1:
        if b.index(o) != 0:
            for i in b[ind:b.index(o)]:
                b[-1] += i
                ind += 1
        ind += 1
        ans.append(str(o))
        o = min(b[b.index(o) + 1:])
    ans.append(str(a[-1]))
    print(str(t) + ' ' + ' '.join(ans))
else:
    o = min(a)
    ind = 0
    while ind < n-1:
        if a.index(o) != 0:
            for i in a[ind:a.index(o)]:
                a[-1] += i
                ind += 1
        ind += 1
        ans.append(o)
        o = min(a[a.index(o)+1:])
    ans.append(a[-1])
    print(*ans)
Copy
a AbdelH2O
Python 3
189 ms
19.8 MB
Runtime Error