#TSQL, 200 bytes
TSQL, 200 bytes
Table variable used as input
DECLARE @ table(a int, b int identity) INSERT @ values(5),(9),(1),(3),(8),(7),(8); WITH c as(SELECT*,rank()over(order by b desc)z FROM @)SELECT g+isnull(sum(-f)over(order by b),0)FROM(SELECT sum(iif(c.b=1,c.a,0))over()g,d.a-lead(d.a)over(order by d.b)f,c.b FROM c,c d WHERE c.b=d.z)d