import sys
input = lambda: sys.stdin.readline().rstrip()

ANS = []
T = int(input())
for _ in range(T):
    N, Q = map(int, input().split())
    A = [int(a) for a in input().split()]
    ans = sum(max(b - a, 0) for a, b in zip([0] + A, A))
    ANS.append(ans)
    for _ in range(Q):
        l, r = map(int, input().split())
        l, r = l-1, r-1
        if l == r:
            ANS.append(ans)
            continue

        ans -= max(A[l] - A[l-1], 0) if l else A[l]
        if l < N - 1: ans -= max(A[l+1] - A[l], 0)
        if r > l + 1: ans -= max(A[r] - A[r-1], 0)
        if r < N - 1: ans -= max(A[r+1] - A[r], 0)

        A[l], A[r] = A[r], A[l]

        ans += max(A[l] - A[l-1], 0) if l else A[l]
        if l < N - 1: ans += max(A[l+1] - A[l], 0)
        if r > l + 1: ans += max(A[r] - A[r-1], 0)
        if r < N - 1: ans += max(A[r+1] - A[r], 0)

        ANS.append(ans)

print("\n".join(map(str, ANS)))


import sys
input = lambda: sys.stdin.readline().rstrip()

ANS = []
T = int(input())
for _ in range(T):
    N, Q = map(int, input().split())
    A = [int(a) for a in input().split()]
    ans = sum(max(b - a, 0) for a, b in zip([0] + A, A))
    ANS.append(ans)
    for _ in range(Q):
        l, r = map(int, input().split())
        if l == r: continue
        l, r = l-1, r-1

        ans -= max(A[l] - A[l-1], 0) if l else A[l]
        if l < N - 1: ans -= max(A[l+1] - A[l], 0)
        if r > l + 1: ans -= max(A[r] - A[r-1], 0)
        if r < N - 1: ans -= max(A[r+1] - A[r], 0)

        A[l], A[r] = A[r], A[l]

        ans += max(A[l] - A[l-1], 0) if l else A[l]
        if l < N - 1: ans += max(A[l+1] - A[l], 0)
        if r > l + 1: ans += max(A[r] - A[r-1], 0)
        if r < N - 1: ans += max(A[r+1] - A[r], 0)

        ANS.append(ans)

print("\n".join(map(str, ANS)))


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import defaultdict
def gift():
    for _ in range(t):
        n, q = list(map(int,input().split()))
        arry = list(map(int,input().split()))
        ops = []
        for i in range(q):
            op = list(map(int,input().split()))
            ops.append(op)
        station = [0] * n
        station[-1]=arry[n-1]
        ans = arry[n-1]
        for i in range(n-1):
            if arry[n-1-i]<arry[n-2-i]:
                tem = arry[n-2-i]-arry[n-1-i]
                station[n-2-i]= tem
                ans += tem
        yield ans

        for i in range(q):
            s, e = ops[i]
            if s==e:
                yield ans
            else:
                sNum, eNum = arry[s-1],arry[e-1]
                arry[s-1],arry[e-1] = arry[e-1],arry[s-1]
                if s>1:
                    ans-=station[s-2]
                    station[s-2]=0
                    if arry[s-1]<arry[s-2]:
                        tem = arry[s-2]-arry[s-1]
                        station[s-2]= tem
                        ans += tem

                ans-=station[s-1]
                station[s-1]=0
                if arry[s]<arry[s-1]:
                    tem = arry[s-1]-arry[s]
                    station[s-1]= tem
                    ans += tem

                if e==n:
                    ans-=station[n-1]
                    station[n-1]=sNum
                    ans+=sNum

                ans-=station[e-2]
                station[e-2]=0
                if arry[e-1]<arry[e-2]:
                    tem = arry[e-2]-arry[e-1]
                    station[e-2] = tem
                    ans += tem

                if e<n:
                    ans-=station[e-1]
                    station[e-1]=0
                    if arry[e]<arry[e-1]:
                        tem = arry[e-1]-arry[e]
                        station[e-1] = tem
                        ans += tem

                yield ans

if __name__ == '__main__':
    t= int(input())
    ans = gift()
    print(*ans,sep='\n')

#"{} {} {}".format(maxele,minele,minele)

# 0 0 0 1 1 1 7

# 9 8 1 7 2

# 1 3 3
# 1 3 2

# 1 2 3
# 1 2 3

# 2 2 3
# 2 1 3


import sys
input = sys.stdin.buffer.readline
from collections import defaultdict
def gift():
    for _ in range(t):
        n, q = list(map(int,input().split()))
        arry = list(map(int,input().split()))
        ops = []
        for i in range(q):
            op = list(map(int,input().split()))
            ops.append(op)
        station = [0] * n
        station[-1]=arry[n-1]
        ans = arry[n-1]
        for i in range(n-1):
            if arry[n-1-i]<arry[n-2-i]:
                tem = arry[n-2-i]-arry[n-1-i]
                station[n-2-i]= tem
                ans += tem
        yield ans

        for i in range(q):
            s, e = ops[i]
            sNum, eNum = arry[s-1],arry[e-1]
            arry[s-1],arry[e-1] = arry[e-1],arry[s-1]
            if s>1:
                ans-=station[s-2]
                station[s-2]=0
                if arry[s-1]<arry[s-2]:
                    tem = arry[s-2]-arry[s-1]
                    station[s-2]= tem
                    ans += tem

            ans-=station[s-1]
            station[s-1]=0
            if arry[s]<arry[s-1]:
                tem = arry[s-1]-arry[s]
                station[s-1]= tem
                ans += tem

            if e==n:
                ans-=station[n-1]
                station[n-1]=sNum
                ans+=sNum
            elif e-s>1:
                ans-=station[e-2]
                station[e-2]=0
                if arry[e-1]<arry[e-2]:
                    tem = arry[e-2]-arry[e-1]
                    station[e-2] = tem
                    ans += tem

            if e<n:
                ans-=station[e-1]
                station[e-1]=0
                if arry[e]<arry[e-1]:
                    tem = arry[e-1]-arry[e]
                    station[e-1] = tem
                    ans += tem

            yield ans

if __name__ == '__main__':
    t= int(input())
    ans = gift()
    print(*ans,sep='\n')

#"{} {} {}".format(maxele,minele,minele)

# 0 0 0 1 1 1 7

# 9 8 1 7 2

# 1 3 3
# 1 3 2

# 1 2 3
# 1 2 3

# 2 2 3
# 2 1 3


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import defaultdict
def gift():
    for _ in range(t):
        n, q = list(map(int,input().split()))
        arry = list(map(int,input().split()))
        ops = []
        for i in range(q):
            op = list(map(int,input().split()))
            ops.append(op)
        station = [0] * n
        station[-1]=arry[n-1]
        ans = arry[n-1]
        for i in range(n-1):
            if arry[n-1-i]<arry[n-2-i]:
                tem = arry[n-2-i]-arry[n-1-i]
                station[n-2-i]= tem
                ans += tem
        yield ans

        for i in range(q):
            s, e = ops[i]
            sNum, eNum = arry[s-1],arry[e-1]
            arry[s-1],arry[e-1] = arry[e-1],arry[s-1]
            if s>1:
                ans-=station[s-2]
                station[s-2]=0
                if arry[s-1]<arry[s-2]:
                    tem = arry[s-2]-arry[s-1]
                    station[s-2]= tem
                    ans += tem

            ans-=station[s-1]
            station[s-1]=0
            if arry[s]<arry[s-1]:
                tem = arry[s-1]-arry[s]
                station[s-1]= tem
                ans += tem

            if e==n:
                ans-=station[n-1]
                station[n-1]=sNum
                ans+=sNum
            elif e-s>1:
                ans-=station[e-2]
                station[e-2]=0
                if arry[e-1]<arry[e-2]:
                    tem = arry[e-2]-arry[e-1]
                    station[e-2] = tem
                    ans += tem

            if e<n:
                ans-=station[e-1]
                station[e-1]=0
                if arry[e]<arry[e-1]:
                    tem = arry[e-1]-arry[e]
                    station[e-1] = tem
                    ans += tem

            yield ans

if __name__ == '__main__':
    t= int(input())
    ans = gift()
    print(*ans,sep='\n')

#"{} {} {}".format(maxele,minele,minele)

# 0 0 0 1 1 1 7

# 9 8 1 7 2

# 1 3 3
# 1 3 2

# 1 2 3
# 1 2 3

# 2 2 3
# 2 1 3


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import defaultdict
def gift():
    for _ in range(t):
        n, q = list(map(int,input().split()))
        arry = list(map(int,input().split()))
        ops = []
        for i in range(q):
            op = list(map(int,input().split()))
            ops.append(op)
        station = [0] * n
        station[-1]=arry[n-1]
        ans = arry[n-1]
        for i in range(n-1):
            if arry[n-1-i]<arry[n-2-i]:
                tem = arry[n-2-i]-arry[n-1-i]
                station[n-2-i]= tem
                ans += tem
        yield ans

        for i in range(q):
            s, e = ops[i]
            if s==e:
                yield ans
            else:
                sNum, eNum = arry[s-1],arry[e-1]
                arry[s-1],arry[e-1] = arry[e-1],arry[s-1]
                if s>1:
                    ans-=station[s-2]
                    station[s-2]=0
                    if arry[s-1]<arry[s-2]:
                        tem = arry[s-2]-arry[s-1]
                        station[s-2]= tem
                        ans += tem

                ans-=station[s-1]
                station[s-1]=0
                if arry[s]<arry[s-1]:
                    tem = arry[s-1]-arry[s]
                    station[s-1]= tem
                    ans += tem

                if e==n:
                    ans-=station[n-1]
                    station[n-1]=sNum
                    ans+=sNum
                elif e-s>1:
                    ans-=station[e-2]
                    station[e-2]=0
                    if arry[e-1]<arry[e-2]:
                        tem = arry[e-2]-arry[e-1]
                        station[e-2] = tem
                        ans += tem

                if e<n:
                    ans-=station[e-1]
                    station[e-1]=0
                    if arry[e]<arry[e-1]:
                        tem = arry[e-1]-arry[e]
                        station[e-1] = tem
                        ans += tem

                yield ans

if __name__ == '__main__':
    t= int(input())
    ans = gift()
    print(*ans,sep='\n')

#"{} {} {}".format(maxele,minele,minele)

# 0 0 0 1 1 1 7

# 9 8 1 7 2

# 1 3 3
# 1 3 2

# 1 2 3
# 1 2 3

# 2 2 3
# 2 1 3


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import defaultdict
def gift():
    for _ in range(t):
        n, q = list(map(int,input().split()))
        arry = list(map(int,input().split()))
        ops = []
        for i in range(q):
            op = list(map(int,input().split()))
            ops.append(op)
        station = [0] * n
        station[-1]=arry[n-1]
        ans = arry[n-1]
        for i in range(n-1):
            if arry[n-1-i]<arry[n-2-i]:
                tem = arry[n-2-i]-arry[n-1-i]
                station[n-2-i]= tem
                ans += tem
        yield ans

        for i in range(q):
            s, e = ops[i]
            if s==e:
                yield ans
            else:
                sNum, eNum = arry[s-1],arry[e-1]
                arry[s-1],arry[e-1] = arry[e-1],arry[s-1]
                if s>1:
                    ans-=station[s-2]
                    station[s-2]=0
                    if arry[s-1]<arry[s-2]:
                        tem = arry[s-2]-arry[s-1]
                        station[s-2]= tem
                        ans += tem

                ans-=station[s-1]
                station[s-1]=0
                if arry[s]<arry[s-1]:
                    tem = arry[s-1]-arry[s]
                    station[s-1]= tem
                    ans += tem

                if e==n:
                    ans-=station[n-1]
                    station[n-1]=sNum
                    ans+=sNum
                elif e-s>2:
                    ans-=station[e-2]
                    station[e-2]=0
                    if arry[e-1]<arry[e-2]:
                        tem = arry[e-2]-arry[e-1]
                        station[e-2] = tem
                        ans += tem

                if e<n:
                    ans-=station[e-1]
                    station[e-1]=0
                    if arry[e]<arry[e-1]:
                        tem = arry[e-1]-arry[e]
                        station[e-1] = tem
                        ans += tem

                yield ans

if __name__ == '__main__':
    t= int(input())
    ans = gift()
    print(*ans,sep='\n')

#"{} {} {}".format(maxele,minele,minele)

# 0 0 0 1 1 1 7

# 9 8 1 7 2

# 1 3 3
# 1 3 2

# 1 2 3
# 1 2 3

# 2 2 3
# 2 1 3


import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#######################################
# def swaps(ind,n):
#     if ind<0 or ind>=n:
#         return
#     elif ind == 0:
#         if a[ind]>a[ind+1]:
#             out[0]+= abs(1-m[ind])*a[ind]
#             m[ind] = 1
#         else:
#             out[0] +=(0-m[ind])*a[ind]
#             m[ind] = 0
#     elif ind == n-1:
#         if a[ind]>a[ind-1]:
#             out[0]+=abs(1-m[ind])*a[ind]
#             m[ind]=1
#         else:
#             out[0]+=(0-m[ind])*a[ind]
#             m[ind]= 0
#     else:
#         if a[ind]>a[ind-1] and a[ind+1]<a[ind]:
#             out[0]+= abs(1-m[ind])*a[ind]
#             m[ind]=1
#         elif a[ind]<a[ind-1] and a[ind]<a[ind+1]:
#             out[0]-=abs(-1-m[ind])*a[ind]
#             m[ind]=-1
#         else:
#             out[0] += (0-m[ind])*a[ind]
#             m[ind]=0
if __name__ == '__main__':
    for _ in range(int(input())):
        n,q = map(int,input().split())
        a = list(map(int,input().split()))
        if n>1:
            m = [0 for i in range(n)]
            k = True
            ans = 0
            for i in range(n):
                if i == 0 and a[i]>a[i+1]:
                    ans += a[i]
                    m[i]=1
                    k = False
                elif i== n-1 and a[i]>a[i-1] and k:
                    ans+= a[i]
                    m[i]=1
                    k = False
                elif i>0 and i<n-1:
                    if a[i]>a[i-1] and a[i]>a[i+1] and k:
                        ans+= a[i]
                        m[i]=1
                        k = False
                    elif a[i]<a[i-1] and a[i]<a[i+1] and not k :
                        ans-= a[i]
                        m[i]=-1
                        k = True
            print(ans)
            out = []
            out.append(ans)
            for i in range(q):
                z = []
                left,right = map(int,input().split())
                a[left-1],a[right-1] = a[right-1],a[left-1]
                m[left-1],m[right-1] = m[right-1],m[left-1]
                z = [left-1,right-1,left,right,left-2,right-2]
                # swaps(left-1,n)
                # swaps(right-1,n)
                # swaps(left,n)
                # swaps(right,n)
                # swaps(left-2,n)
                # swaps(right-2,n)
                for ind in z:
                    if ind<0 or ind>=n:
                        continue
                    elif ind == 0:
                        if a[ind]>a[ind+1]:
                            out[0]+= abs(1-m[ind])*a[ind]
                            m[ind] = 1
                        else:
                            out[0] +=(0-m[ind])*a[ind]
                            m[ind] = 0
                    elif ind == n-1:
                        if a[ind]>a[ind-1]:
                            out[0]+=abs(1-m[ind])*a[ind]
                            m[ind]=1
                        else:
                            out[0]+=(0-m[ind])*a[ind]
                            m[ind]= 0
                    else:
                        if a[ind]>a[ind-1] and a[ind+1]<a[ind]:
                            out[0]+= abs(1-m[ind])*a[ind]
                            m[ind]=1
                        elif a[ind]<a[ind-1] and a[ind]<a[ind+1]:
                            out[0]-=abs(-1-m[ind])*a[ind]
                            m[ind]=-1
                        else:
                            out[0] += (0-m[ind])*a[ind]
                            m[ind]=0
                print(out[0])
        else:
            print(a[0])
            for _ in range(q):
                left,right = map(int,input().split())
                print(a[0])


import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#######################################
# def swaps(ind,n):
#     if ind<0 or ind>=n:
#         return
#     elif ind == 0:
#         if a[ind]>a[ind+1]:
#             out[0]+= abs(1-m[ind])*a[ind]
#             m[ind] = 1
#         else:
#             out[0] +=(0-m[ind])*a[ind]
#             m[ind] = 0
#     elif ind == n-1:
#         if a[ind]>a[ind-1]:
#             out[0]+=abs(1-m[ind])*a[ind]
#             m[ind]=1
#         else:
#             out[0]+=(0-m[ind])*a[ind]
#             m[ind]= 0
#     else:
#         if a[ind]>a[ind-1] and a[ind+1]<a[ind]:
#             out[0]+= abs(1-m[ind])*a[ind]
#             m[ind]=1
#         elif a[ind]<a[ind-1] and a[ind]<a[ind+1]:
#             out[0]-=abs(-1-m[ind])*a[ind]
#             m[ind]=-1
#         else:
#             out[0] += (0-m[ind])*a[ind]
#             m[ind]=0
if __name__ == '__main__':
    for _ in range(int(input())):
        n,q = map(int,input().split())
        a = list(map(int,input().split()))
        m = [0 for i in range(n)]
        k = True
        ans = 0
        for i in range(n):
            if i == 0 and a[i]>a[i+1]:
                ans += a[i]
                m[i]=1
                k = False
            elif i== n-1 and a[i]>a[i-1] and k:
                ans+= a[i]
                m[i]=1
                k = False
            elif i>0 and i<n-1:
                if a[i]>a[i-1] and a[i]>a[i+1] and k:
                    ans+= a[i]
                    m[i]=1
                    k = False
                elif a[i]<a[i-1] and a[i]<a[i+1] and not k :
                    ans-= a[i]
                    m[i]=-1
                    k = True
        print(ans)
        out = []
        out.append(ans)
        for i in range(q):
            z = []
            left,right = map(int,input().split())
            a[left-1],a[right-1] = a[right-1],a[left-1]
            m[left-1],m[right-1] = m[right-1],m[left-1]
            z = [left-1,right-1,left,right,left-2,right-2]
            # swaps(left-1,n)
            # swaps(right-1,n)
            # swaps(left,n)
            # swaps(right,n)
            # swaps(left-2,n)
            # swaps(right-2,n)
            for ind in z:
                if ind<0 or ind>=n:
                    continue
                elif ind == 0:
                    if a[ind]>a[ind+1]:
                        out[0]+= abs(1-m[ind])*a[ind]
                        m[ind] = 1
                    else:
                        out[0] +=(0-m[ind])*a[ind]
                        m[ind] = 0
                elif ind == n-1:
                    if a[ind]>a[ind-1]:
                        out[0]+=abs(1-m[ind])*a[ind]
                        m[ind]=1
                    else:
                        out[0]+=(0-m[ind])*a[ind]
                        m[ind]= 0
                else:
                    if a[ind]>a[ind-1] and a[ind+1]<a[ind]:
                        out[0]+= abs(1-m[ind])*a[ind]
                        m[ind]=1
                    elif a[ind]<a[ind-1] and a[ind]<a[ind+1]:
                        out[0]-=abs(-1-m[ind])*a[ind]
                        m[ind]=-1
                    else:
                        out[0] += (0-m[ind])*a[ind]
                        m[ind]=0
            print(out[0])


def swaps(x,n):
    if x!=0 and x!=n+1:
        if l[x]>l[x-1] and l[x]>l[x+1]:
            ans[0]+= abs(1-a[x-1])*l[x]
            a[x-1] = 1
        elif l[x]<l[x-1] and l[x]<l[x+1]:
            ans[0]-=abs(-1-a[x-1])*l[x]
            a[x-1] = -1
        else:
            ans[0]+=(0-a[x-1])*l[x]
            a[x-1] = 0
    return
if __name__ == '__main__':
    for _ in range(int(input())):
        n,q = map(int,input().split())
        a = list(map(int,input().split()))
        k = -float('inf')
        l = list()
        l.append(k)
        l+=a
        l.append(k)
        a = []
        k = True
        ans = [0]
        a = [0 for i in range(n)]
        # print(l)
        for i in range(1,n+1):
            if l[i]>l[i+1] and l[i]>l[i-1] and k:
                ans[0] += l[i]
                a[i-1] +=1
                k = False
            elif l[i]<l[i+1] and not k:
                ans[0]-=l[i]
                k = True
                a[i-1]-=1
            else:
                a.append(0)
        print(ans[0])
        for j in range(q):
            l1,r1 = map(int,input().split())
            l[l1],l[r1] = l[r1],l[l1]
            a[l1-1],a[r1-1] = a[r1-1],a[l1-1]
            swaps(l1,n)
            swaps(l1-1,n)
            swaps(l1+1,n)
            swaps(r1,n)
            swaps(r1+1,n)
            swaps(r1-1,n)
            print(ans[0])


def swaps(x,n):
    if x!=0 and x!=n+1:
        if l[x]>l[x-1] and l[x]>l[x+1]:
            ans[0]+= abs(1-a[x-1])*l[x]
            a[x-1] = 1
        elif l[x]<l[x-1] and l[x]<l[x+1]:
            ans[0]-=abs(-1-a[x-1])*l[x]
            a[x-1] = -1
        else:
            ans[0]+=(0-a[x-1])*l[x]
            a[x-1] = 0
if __name__ == '__main__':
    for _ in range(int(input())):
        n,q = map(int,input().split())
        a = list(map(int,input().split()))
        k = -float('inf')
        l = list()
        l.append(k)
        l+=a
        l.append(k)
        a = []
        k = True
        ans = [0]
        # print(l)
        for i in range(1,n+1):
            if l[i]>l[i+1] and l[i]>l[i-1] and k:
                ans[0] += l[i]
                a.append(1)
                k = False
            elif l[i]<l[i+1] and not k:
                ans[0]-=l[i]
                k = True
                a.append(-1)
            else:
                a.append(0)
        print(ans[0])
        for i in range(q):
            l1,r1 = map(int,input().split())
            l[l1],l[r1] = l[r1],l[l1]
            a[l1-1],a[r1-1] = a[r1-1],a[l1-1]
            swaps(l1,n)
            swaps(l1-1,n)
            swaps(l1+1,n)
            swaps(r1,n)
            swaps(r1+1,n)
            swaps(r1-1,n)
            print(ans[0])


import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#######################################
def swaps(ind,n):
    if ind<0 or ind>=n:
        return
    elif ind == 0:
        if a[ind]>a[ind+1]:
            out[0]+= abs(1-m[ind])*a[ind]
            m[ind] = 1
        else:
            out[0] +=(0-m[ind])*a[ind]
            m[ind] = 0
    elif ind == n-1:
        if a[ind]>a[ind-1]:
            out[0]+=abs(1-m[ind])*a[ind]
            m[ind]=1
        else:
            out[0]+=(0-m[ind])*a[ind]
            m[ind]= 0
    else:
        if a[ind]>a[ind-1] and a[ind+1]<a[ind]:
            out[0]+= abs(1-m[ind])*a[ind]
            m[ind]=1
        elif a[ind]<a[ind-1] and a[ind]<a[ind+1]:
            out[0]-=abs(-1-m[ind])*a[ind]
            m[ind]=-1
        else:
            out[0] += (0-m[ind])*a[ind]
            m[ind]=0
if __name__ == '__main__':
    for _ in range(int(input())):
        n,q = map(int,input().split())
        a = list(map(int,input().split()))
        m = [0 for i in range(n)]
        k = True
        ans = 0
        for i in range(n):
            if i == 0 and a[i]>a[i+1]:
                ans += a[i]
                m[i]=1
                k = False
            elif i== n-1 and a[i]>a[i-1] and k:
                ans+= a[i]
                m[i]=1
                k = False
            elif i>0 and i<n-1:
                if a[i]>a[i-1] and a[i]>a[i+1] and k:
                    ans+= a[i]
                    m[i]=1
                    k = False
                elif a[i]<a[i-1] and a[i]<a[i+1] and not k :
                    ans-= a[i]
                    m[i]=-1
                    k = True
        print(ans)
        # print(m)
        out = list()
        out.append(ans)
        for i in range(q):
            left,right = map(int,input().split())
            a[left-1],a[right-1] = a[right-1],a[left-1]
            m[left-1],m[right-1] = m[right-1],m[left-1]
            swaps(left-1,n)
            swaps(right-1,n)
            swaps(left,n)
            swaps(right,n)
            swaps(left-2,n)
            swaps(right-2,n)
            print(out[0])
            # print(m)


def swaps(x):
    if x!=0 and x!=n+1:
        if l[x]>l[x-1] and l[x]>l[x+1]:
            ans[0]+= abs(1-a[x-1])*l[x]
            a[x-1] = 1
        elif l[x]<l[x-1] and l[x]<l[x+1]:
            ans[0]-=abs(-1-a[x-1])*l[x]
            a[x-1] = -1
        else:
            ans[0]+=(0-a[x-1])*l[x]
            a[x-1] = 0
if __name__ == '__main__':
    for _ in range(int(input())):
        n,q = map(int,input().split())
        a = list(map(int,input().split()))
        k = -float('inf')
        l = list()
        l.append(k)
        l+=a
        l.append(k)
        a = []
        k = True
        ans = [0]
        # print(l)
        for i in range(1,n+1):
            if l[i]>l[i+1] and l[i]>l[i-1] and k:
                ans[0] += l[i]
                a.append(1)
                k = False
            elif l[i]<l[i+1] and not k:
                ans[0]-=l[i]
                k = True
                a.append(-1)
            else:
                a.append(0)
        print(ans[0])
        for i in range(q):
            l1,r1 = map(int,input().split())
            l[l1],l[r1] = l[r1],l[l1]
            a[l1-1],a[r1-1] = a[r1-1],a[l1-1]
            swaps(l1)
            swaps(l1-1)
            swaps(l1+1)
            swaps(r1)
            swaps(r1+1)
            swaps(r1-1)
            print(ans[0])


import sys

def big(i):
	global a
	return (a[i] > a[i - 1]) and (a[i] >= a[i + 1])

def little(i):
	global a
	return (a[i] <= a[i - 1]) and (a[i] < a[i + 1])

def make(a, i, x):
	global s
	if big(i):
		s -= a[i]
	if little(i):
		s += a[i]
	if big(i - 1):
		s -= a[i - 1]
	if little(i - 1):
		s += a[i - 1]
	if big(i + 1):
		s -= a[i + 1]
	if little(i + 1):
		s += a[i + 1]

	a[i] = x

	if big(i):
		s += a[i]
	if little(i):
		s -= a[i]
	if big(i - 1):
		s += a[i - 1]
	if little(i - 1):
		s -= a[i - 1]
	if big(i + 1):
		s += a[i + 1]
	if little(i + 1):
		s -= a[i + 1]

t = int(input())
for I in range(t):
	n, q = map(int, sys.stdin.readline().split())
	a = list(map(int, sys.stdin.readline().split()))
	a.append(0)
	a.append(0)
	up = True
	s = 0
	for i in range(n):
		if up:
			if a[i] > a[i - 1]:
				s += a[i] - a[i - 1]
			else:
				up = False
		else:
			if a[i] > a[i - 1]:
				up = True
				s += a[i] - a[i - 1]
	print(s)
	for i in range(q):
		l, r = map(int, sys.stdin.readline().split())
		l -= 1
		r -= 1
		ll = a[l]
		rr = a[r]
		make(a, l, rr)
		make(a, r, ll)
		print(s)


def big(i):
	global a
	return (i > 0) and (i < len(a) - 1) and (a[i] > a[i - 1]) and (a[i] >= a[i + 1])

def little(i):
	global a
	return (i == 0) or (i == len(a) - 1) or ((a[i] <= a[i - 1]) and (a[i] < a[i + 1]))

def make(a, i, x):
	global s
	if big(i):
		s -= a[i]
	if little(i):
		s += a[i]
	if big(i - 1):
		s -= a[i - 1]
	if little(i - 1):
		s += a[i - 1]
	if big(i + 1):
		s -= a[i + 1]
	if little(i + 1):
		s += a[i + 1]

	a[i] = x

	if big(i):
		s += a[i]
	if little(i):
		s -= a[i]
	if big(i - 1):
		s += a[i - 1]
	if little(i - 1):
		s -= a[i - 1]
	if big(i + 1):
		s += a[i + 1]
	if little(i + 1):
		s -= a[i + 1]

t = int(input())
for I in range(t):
	n, q = map(int, input().split())
	a = [0] + list(map(int, input().split())) + [0]
	n += 2
	up = True
	s = a[0]
	for i in range(1, n):
		if up:
			if a[i] > a[i - 1]:
				s += a[i] - a[i - 1]
			else:
				up = False
		else:
			if a[i] > a[i - 1]:
				up = True
				s += a[i] - a[i - 1]
	ans = [s]
	for i in range(q):
		l, r = map(int, input().split())
		ll = a[l]
		rr = a[r]
		make(a, l, rr)
		make(a, r, ll)
		ans.append(s)
	for i in ans:
		print(i)


def big(i):
	global a
	return (i > 0) and (i < len(a) - 1) and (a[i] > a[i - 1]) and (a[i] >= a[i + 1])

def little(i):
	global a
	return (i == 0) or (i == len(a) - 1) or ((a[i] <= a[i - 1]) and (a[i] < a[i + 1]))

def make(a, i, x):
	global s
	if big(i):
		s -= a[i]
	if little(i):
		s += a[i]
	if big(i - 1):
		s -= a[i - 1]
	if little(i - 1):
		s += a[i - 1]
	if big(i + 1):
		s -= a[i + 1]
	if little(i + 1):
		s += a[i + 1]

	a[i] = x

	if big(i):
		s += a[i]
	if little(i):
		s -= a[i]
	if big(i - 1):
		s += a[i - 1]
	if little(i - 1):
		s -= a[i - 1]
	if big(i + 1):
		s += a[i + 1]
	if little(i + 1):
		s -= a[i + 1]

t = int(input())
for I in range(t):
	n, q = map(int, input().split())
	a = [0] + list(map(int, input().split())) + [0]
	n += 2
	up = True
	s = a[0]
	for i in range(1, n):
		if up:
			if a[i] > a[i - 1]:
				s += a[i] - a[i - 1]
			else:
				up = False
		else:
			if a[i] > a[i - 1]:
				up = True
				s += a[i] - a[i - 1]
	print(s)
	for i in range(q):
		l, r = map(int, input().split())
		ll = a[l]
		rr = a[r]
		make(a, l, rr)
		make(a, r, ll)
		print(s)


def big(i):
	global a
	return (a[i] > a[i - 1]) and (a[i] >= a[i + 1])

def little(i):
	global a
	return (a[i] <= a[i - 1]) and (a[i] < a[i + 1])

def make(a, i, x):
	global s
	if big(i):
		s -= a[i]
	if little(i):
		s += a[i]
	if big(i - 1):
		s -= a[i - 1]
	if little(i - 1):
		s += a[i - 1]
	if big(i + 1):
		s -= a[i + 1]
	if little(i + 1):
		s += a[i + 1]

	a[i] = x

	if big(i):
		s += a[i]
	if little(i):
		s -= a[i]
	if big(i - 1):
		s += a[i - 1]
	if little(i - 1):
		s -= a[i - 1]
	if big(i + 1):
		s += a[i + 1]
	if little(i + 1):
		s -= a[i + 1]

t = int(input())
for I in range(t):
	n, q = map(int, input().split())
	a = list(map(int, input().split()))
	a.append(0)
	a.append(0)
	up = True
	s = 0
	for i in range(n):
		if up:
			if a[i] > a[i - 1]:
				s += a[i] - a[i - 1]
			else:
				up = False
		else:
			if a[i] > a[i - 1]:
				up = True
				s += a[i] - a[i - 1]
	print(s)
	for i in range(q):
		l, r = map(int, input().split())
		l -= 1
		r -= 1
		ll = a[l]
		rr = a[r]
		make(a, l, rr)
		make(a, r, ll)
		print(s)


def big(i):
	global a
	return (i > 0) and (i < len(a) - 1) and (a[i] > a[i - 1]) and (a[i] >= a[i + 1])

def little(i):
	global a
	return (i == 0) or (i == len(a) - 1) or ((a[i] <= a[i - 1]) and (a[i] < a[i + 1]))

def make(a, i, x):
	global s
	if big(i):
		s -= a[i]
	if little(i):
		s += a[i]
	if big(i - 1):
		s -= a[i - 1]
	if little(i - 1):
		s += a[i - 1]
	if big(i + 1):
		s -= a[i + 1]
	if little(i + 1):
		s += a[i + 1]

	a[i] = x

	if big(i):
		s += a[i]
	if little(i):
		s -= a[i]
	if big(i - 1):
		s += a[i - 1]
	if little(i - 1):
		s -= a[i - 1]
	if big(i + 1):
		s += a[i + 1]
	if little(i + 1):
		s -= a[i + 1]

t = int(input())
for I in range(t):
	n, q = map(int, input().split())
	a = list(map(int, input().split()))
	a.append(0)
	a.append(0)
	n += 2
	up = True
	s = a[0]
	for i in range(1, n):
		if up:
			if a[i] > a[i - 1]:
				s += a[i] - a[i - 1]
			else:
				up = False
		else:
			if a[i] > a[i - 1]:
				up = True
				s += a[i] - a[i - 1]
	print(s)
	for i in range(q):
		l, r = map(int, input().split())
		l -= 1
		r -= 1
		ll = a[l]
		rr = a[r]
		make(a, l, rr)
		make(a, r, ll)
		print(s)


def add(f, i, x):
	while i < len(f):
		f[i] += x
		i |= (i + 1)

def sum(f, i): # from 0 to i
	if i < 0:
		return 0
	else:
		return f[i] + sum(f, (i & (i + 1)) - 1)

def big(i):
	global a
	return (i > 0) and (i < len(a) - 1) and (a[i] > a[i - 1]) and (a[i] >= a[i + 1])

def little(i):
	global a
	return (i == 0) or (i == len(a) - 1) or ((a[i] <= a[i - 1]) and (a[i] < a[i + 1]))

def make(a, i, x, f):
	global s
	if big(i):
		s -= a[i]
	if little(i):
		s += a[i]
	if big(i - 1):
		s -= a[i - 1]
	if little(i - 1):
		s += a[i - 1]
	if big(i + 1):
		s -= a[i + 1]
	if little(i + 1):
		s += a[i + 1]

	a[i] = x

	if big(i):
		s += a[i]
	if little(i):
		s -= a[i]
	if big(i - 1):
		s += a[i - 1]
	if little(i - 1):
		s -= a[i - 1]
	if big(i + 1):
		s += a[i + 1]
	if little(i + 1):
		s -= a[i + 1]

t = int(input())
for I in range(t):
	n, q = map(int, input().split())
	a = [0] + list(map(int, input().split())) + [0]
	n += 2
	up = True
	s = a[0]
	f = [0 for i in range(n)]
	add(f, 0, 1)
	for i in range(1, n):
		if up:
			if a[i] > a[i - 1]:
				add(f, i - 1, -1)
				add(f, i, 1)
				s += a[i] - a[i - 1]
			else:
				up = False
				add(f, i, 1)
		else:
			if a[i] > a[i - 1]:
				add(f, i - 1, 1)
				add(f, i, 1)
				up = True
				s += a[i] - a[i - 1]
	ans = [s]
	for i in range(q):
		l, r = map(int, input().split())
		ll = a[l]
		rr = a[r]
		make(a, l, rr, f)
		make(a, r, ll, f)
		ans.append(s)
	for i in ans:
		print(i)


import itertools
import math
import sys
from collections import defaultdict

def stdinWrapper():
    data = '''3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
'''

    for line in data.split('\n'):
        yield line

if '--debug' not in sys.argv:
    def stdinWrapper():
        while True:
            yield input()

inputs = stdinWrapper()

def inputWrapper():
    return next(inputs)

def getType(_type):
    return _type(inputWrapper())

def getArray(_type):
    return [_type(x) for x in inputWrapper().split()]

''' Solution '''

def solve(a, queries):
    d = []
    for i in range(len(a) - 1):
        d.append(a[i] - a[i+1])

    results = []
    def get_current_result():
        look_positive = True
        res = 0
        for i in range(len(d)):
            if d[i] > 0 and look_positive:
                res += a[i]
                look_positive = False

            elif d[i] < 0 and not look_positive:
                res -= a[i]
                look_positive = True

        if look_positive:
            res += a[-1]

        return res

    results.append(get_current_result())
    for l,r in queries:
        # do swap in a and d
        to_update = set()
        l-=1
        r-=1
        tmp = a[l]
        a[l] = a[r]
        a[r] = tmp
        for i in [l, l-1, r, r-1]:
            if i >= 0 and i<(len(a)-1):
                d[i] = a[i] - a[i+1]

        results.append(get_current_result())

    return [str(x) for x in results]

t = getType(int)

for _ in range(t):
    n, q = getArray(int)
    a = getArray(int)
    queries = [getArray(int) for _ in range(q)]
    res = solve(a, queries)
    print('\n'.join(res))


import itertools
import math
import sys
from collections import defaultdict

def stdinWrapper():
    data = '''3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3

'''

    for line in data.split('\n'):
        yield line

if '--debug' not in sys.argv:
    def stdinWrapper():
        while True:
            yield sys.stdin.readline()

inputs = stdinWrapper()

def inputWrapper():
    return next(inputs)

def getType(_type):
    return _type(inputWrapper())

def getArray(_type):
    return [_type(x) for x in inputWrapper().split()]

''' Solution '''

def solve(a, queries):
    results = []
    res = 0
    a = [-1] + a + [-1]

    def check(res, i, remove=False):
        k = 1
        if remove:
            k = -1
        if a[i] > a[i-1] and a[i] > a[i+1]:
            return res + a[i] * k
        elif a[i] < a[i-1] and a[i] < a[i+1]:
            return res - a[i] * k

        return res

    for i in range(1, len(a)-1):
        res = check(res, i)

    results.append(res)

    for l, r in queries:
        affected = {l, r, max(1, l-1), max(1, r-1), min(len(a)-2, l+1), min(len(a)-2, r+1)}
        for x in affected:
            res = check(res, x, True)
        tmp = a[l]
        a[l] = a[r]
        a[r] = tmp
        for x in affected:
            res = check(res, x)

        results.append(res)

    return results

t = getType(int)

for _ in range(t):
    n, q = getArray(int)

    a = getArray(int)
    queries = [getArray(int) for _ in range(q)]
    res = solve(a, queries)
    print('\n'.join([str(x) for x in res]))


import itertools
import math
import sys
from collections import defaultdict

def stdinWrapper():
    data = '''3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3

'''

    for line in data.split('\n'):
        yield line

if '--debug' not in sys.argv:
    def stdinWrapper():
        while True:
            yield input()

inputs = stdinWrapper()

def inputWrapper():
    return next(inputs)

def getType(_type):
    return _type(inputWrapper())

def getArray(_type):
    return [_type(x) for x in inputWrapper().split()]

''' Solution '''

def solve(a, queries):
    look_positive = True
    results = []
    res = 0
    a = [-1] + a + [-1]

    def check(res, i, remove=False):
        k = 1
        if remove:
            k = -1
        if a[i] > a[i-1] and a[i] > a[i+1]:
            return res + a[i] * k
        elif a[i] < a[i-1] and a[i] < a[i+1]:
            return res - a[i] * k

        return res

    for i in range(1, len(a)-1):
        res = check(res, i)

    results.append(res)

    for l, r in queries:
        affected = {l, r, max(1, l-1), max(1, r-1), min(len(a)-2, l+1), min(len(a)-2, r+1)}
        for x in affected:
            res = check(res, x, True)
        tmp = a[l]
        a[l] = a[r]
        a[r] = tmp
        for x in affected:
            res = check(res, x)

        results.append(res)

    return results

t = getType(int)

for _ in range(t):
    n, q = getArray(int)

    a = getArray(int)
    queries = [getArray(int) for _ in range(q)]
    res = solve(a, queries)
    print('\n'.join([str(x) for x in res]))


# import numpy as npy
# idx=sorted(idx,key=functools.cmp_to_key(cmpx))
import bisect
import array
import functools
import math

input=__import__('sys').stdin.readline

def solve():
    n,Q=map(int,input().split())
    a=array.array('i',map(int,input().split()))

    def jud(x):
        if x<0 or x>=n:
            return 0
        p,s=0,0
        if x!=0:
            p=a[x-1]
        if x+1!=n:
            s=a[x+1]
        if p<a[x] and s<=a[x]:
            return a[x]
        if p>a[x] and s>=a[x]:
            return -a[x]
        return 0

    ans=0
    for i in range(n):
        ans=ans+jud(i)
    print(ans)

    for i in range(Q):
        x,y=map(int,input().split())
        kx,ky=a[x-1],a[y-1]

        ans=ans-jud(x-2)-jud(x-1)-jud(x)
        a[x-1]=ky
        ans=ans+jud(x-2)+jud(x-1)+jud(x)

        ans=ans-jud(y-2)-jud(y-1)-jud(y)
        a[y-1]=kx
        ans=ans+jud(y-2)+jud(y-1)+jud(y)

        print(ans)

T=int(input())

for Tid in range(T):
    solve()


# import numpy as npy
# idx=sorted(idx,key=functools.cmp_to_key(cmpx))
import bisect
import array
import functools
import math

def solve():
    n,Q=map(int,input().split())
    a=array.array('i',map(int,input().split()))

    def jud(x):
        if x<0 or x>=n:
            return 0
        p,s=0,0
        if x!=0:
            p=a[x-1]
        if x+1!=n:
            s=a[x+1]
        if p<a[x] and s<=a[x]:
            return a[x]
        if p>a[x] and s>=a[x]:
            return -a[x]
        return 0

    ans=0
    for i in range(n):
        ans=ans+jud(i)
    print(ans)

    for i in range(Q):
        x,y=map(int,input().split())
        kx,ky=a[x-1],a[y-1]

        ans=ans-jud(x-2)-jud(x-1)-jud(x)
        a[x-1]=ky
        ans=ans+jud(x-2)+jud(x-1)+jud(x)

        ans=ans-jud(y-2)-jud(y-1)-jud(y)
        a[y-1]=kx
        ans=ans+jud(y-2)+jud(y-1)+jud(y)

        print(ans)

T=int(input())

for Tid in range(T):
    solve()


# import numpy as npy
# idx=sorted(idx,key=functools.cmp_to_key(cmpx))
import bisect
import functools
import math

def solve():
    n,Q=map(int,input().split())
    a=list(map(int,input().split()))

    def jud(x):
        if x<0 or x>=n:
            return 0
        p,s=0,0
        if x!=0:
            p=a[x-1]
        if x+1!=n:
            s=a[x+1]
        if p<a[x] and s<=a[x]:
            return a[x]
        if p>a[x] and s>=a[x]:
            return -a[x]
        return 0

    ans=0
    for i in range(n):
        ans=ans+jud(i)
    print(ans)

    for i in range(Q):
        x,y=map(int,input().split())
        kx,ky=a[x-1],a[y-1]

        ans=ans-jud(x-2)-jud(x-1)-jud(x)
        a[x-1]=ky
        ans=ans+jud(x-2)+jud(x-1)+jud(x)

        ans=ans-jud(y-2)-jud(y-1)-jud(y)
        a[y-1]=kx
        ans=ans+jud(y-2)+jud(y-1)+jud(y)

        print(ans)

T=int(input())

for Tid in range(T):
    solve()


from sys import stdin

tt = int(stdin.readline())
pls = []

for loop in range(tt):

    n,q = map(int,stdin.readline().split())
    a   = list(map(int,stdin.readline().split()))
    a = [0] + a + [0]

    lis = [0] * len(a)

    ans = 0
    for i in range(1,len(a)-1):
        if a[i-1] < a[i] and a[i] > a[i+1]:
            lis[i] = 1
            ans += a[i]
        elif a[i-1] > a[i] and a[i] < a[i+1]:
            lis[i] = -1
            ans -= a[i]

    pls.append(ans)

    for loop in range(q):

        l,r = map(int,stdin.readline().split())
        if l == r:
            pls.append(ans)
            continue
        ch = {}
        ch[l-1] = 0
        ch[l] = 0
        ch[l+1] = 0
        ch[r-1] = 0
        ch[r] = 0
        ch[r+1] = 0

        for i in ch:
            ans -= a[i] * lis[i]

        a[l],a[r] = a[r],a[l]

        for i in ch:
            if i == 0 or i == len(a)-1:
                pass
            elif a[i-1] < a[i] and a[i] > a[i+1]:
                lis[i] = 1
                ans += a[i]
            elif a[i-1] > a[i] and a[i] < a[i+1]:
                lis[i] = -1
                ans -= a[i]
            else:
                lis[i] = 0
        pls.append(ans)

print ("\n".join(map(str,pls)))


# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
#import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# -------------------game starts now----------------------------------------------------import math
class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1

class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                    self._rotate_right(n.right)
                self._rotate_left(n)
            else:
                n = n.parent

    def _remove_one(self, node):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        replacement = node.left or node.right
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = replacement
            else:
                node.parent.right = replacement
            replacement.parent = node.parent
            node.parent = None
        else:
            self._tree = replacement
            replacement.parent = None
        node.left = None
        node.right = None
        node.parent = None
        self._rebalance(replacement)

    def _remove_leaf(self, node):
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = None
            else:
                node.parent.right = None
            self._rebalance(node.parent)
        else:
            self._tree = None
        node.parent = None
        node.left = None
        node.right = None

    def remove(self, k):
        node = self._get_node(k)
        if not node:
            return
        if AvlTree._is_leaf(node):
            self._remove_leaf(node)
            return
        if node.left and node.right:
            nxt = AvlTree._get_next(node)
            node.key = nxt.key
            node.value = nxt.value
            if self._is_leaf(nxt):
                self._remove_leaf(nxt)
            else:
                self._remove_one(nxt)
            self._rebalance(node)
        else:
            self._remove_one(node)

    def get(self, k):
        node = self._get_node(k)
        return node.value if node else -1

    def _get_node(self, k):
        if not self._tree:
            return None
        node = self._tree
        while node:
            if k < node.key:
                node = node.left
            elif node.key < k:
                node = node.right
            else:
                return node
        return None

    def get_at(self, pos):
        x = pos + 1
        node = self._tree
        while node:
            if x < node.num_left:
                node = node.left
            elif node.num_left < x:
                x -= node.num_left
                node = node.right
            else:
                return (node.key, node.value)
        raise IndexError("Out of ranges")

    @staticmethod
    def _is_left(node):
        return node.parent.left and node.parent.left == node

    @staticmethod
    def _is_leaf(node):
        return node.left is None and node.right is None

    def _rotate_right(self, node):
        if not node.parent:
            self._tree = node.left
            node.left.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.left
            node.left.parent = node.parent
        else:
            node.parent.right = node.left
            node.left.parent = node.parent
        bk = node.left.right
        node.left.right = node
        node.parent = node.left
        node.left = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    def _rotate_left(self, node):
        if not node.parent:
            self._tree = node.right
            node.right.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.right
            node.right.parent = node.parent
        else:
            node.parent.right = node.right
            node.right.parent = node.parent
        bk = node.right.left
        node.right.left = node
        node.parent = node.right
        node.right = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    @staticmethod
    def _get_next(node):
        if not node.right:
            return node.parent
        n = node.right
        while n.left:
            n = n.left
        return n

# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default=300006, func=lambda a, b: min(a , b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b:a + b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m

# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z

# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por

# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left) / 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid] <key):
            count = mid + 1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count

# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c
def binary(x, length):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

def countGreater(arr, n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] > k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)

# --------------------------------------------------binary------------------------------------
class TrieNode:
    def __init__(self):
        self.children = [None] * 26
        self.isEndOfWord = False
class Trie:
    def __init__(self):
        self.root = self.getNode()
    def getNode(self):
        return TrieNode()
    def _charToIndex(self, ch):
        return ord(ch) - ord('a')
    def insert(self, key):
        pCrawl = self.root
        length = len(key)
        for level in range(length):
            index = self._charToIndex(key[level])
            if not pCrawl.children[index]:
                pCrawl.children[index] = self.getNode()
            pCrawl = pCrawl.children[index]
        pCrawl.isEndOfWord = True
    def search(self, key):
        pCrawl = self.root
        length = len(key)
        for level in range(length):
            index = self._charToIndex(key[level])
            if not pCrawl.children[index]:
                return False
            pCrawl = pCrawl.children[index]
        return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
    def __init__(self, data):
        self.data = data
        self.count=0
        self.left = None  # left node for 0
        self.right = None  # right node for 1
class BinaryTrie:
    def __init__(self):
        self.root = Node(0)
    def insert(self, pre_xor):
        self.temp = self.root
        for i in range(31, -1, -1):
            val = pre_xor & (1 << i)
            if val:
                if not self.temp.right:
                    self.temp.right = Node(0)
                self.temp = self.temp.right
                self.temp.count+=1
            if not val:
                if not self.temp.left:
                    self.temp.left = Node(0)
                self.temp = self.temp.left
                self.temp.count += 1
        self.temp.data = pre_xor
    def query(self, xor):
        self.temp = self.root
        for i in range(31, -1, -1):
            val = xor & (1 << i)
            if not val:
                if self.temp.left and self.temp.left.count>0:
                    self.temp = self.temp.left
                elif self.temp.right:
                    self.temp = self.temp.right
            else:
                if self.temp.right and self.temp.right.count>0:
                    self.temp = self.temp.right
                elif self.temp.left:
                    self.temp = self.temp.left
            self.temp.count-=1
        return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
for ik in range(int(input())):
    n,q=map(int,input().split())
    l=list(map(int,input().split()))
    if n==1:
        print(l[0])
        for i in range(q):
            a,b=map(int,input().split())
            print(l[0])
        continue
    ans=0
    for i in range(n):
        if i==0:
            if l[i]>l[i+1]:
                ans+=l[i]
        elif i==n-1:
            if l[i]>l[i-1]:
                ans+=l[i]
        elif l[i]>l[i-1] and l[i]>l[i+1]:
            ans+=l[i]
        elif l[i]<l[i-1] and l[i]<l[i+1]:
            ans-=l[i]
    print(ans)
    def remove(i,ans):
        if i==0:
            if l[i]>l[i+1]:
                ans-=l[i]
        elif i==n-1:
            if l[i]>l[i-1]:
                ans-=l[i]
        elif l[i]>l[i-1] and l[i]>l[i+1]:
            ans-=l[i]
        elif l[i]<l[i-1] and l[i]<l[i+1]:
            ans+=l[i]
        return ans
    def add(i,ans):
        if i == 0:
            if l[i] > l[i + 1]:
                ans += l[i]
        elif i == n - 1:
            if l[i] > l[i - 1]:
                ans += l[i]
        elif l[i]>l[i-1] and l[i]>l[i+1]:
            ans+=l[i]
        elif l[i]<l[i-1] and l[i]<l[i+1]:
            ans-=l[i]
        return ans
    for j in range(q):
        a,b=map(int,input().split())
        a-=1
        b-=1
        ind=set()
        if a!=0:
            ind.add(a-1)
        if a!=n-1:
            ind.add(a+1)
        ind.add(a)
        if b!=0:
            ind.add(b-1)
        if b!=n-1:
            ind.add(b+1)
        ind.add(b)
        for i in ind:
            ans=remove(i,ans)
        l[a], l[b] = l[b], l[a]
        for i in ind:
            ans = add(i, ans)
        print(ans)


# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
#import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# -------------------game starts now----------------------------------------------------import math
class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1

class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                    self._rotate_right(n.right)
                self._rotate_left(n)
            else:
                n = n.parent

    def _remove_one(self, node):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        replacement = node.left or node.right
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = replacement
            else:
                node.parent.right = replacement
            replacement.parent = node.parent
            node.parent = None
        else:
            self._tree = replacement
            replacement.parent = None
        node.left = None
        node.right = None
        node.parent = None
        self._rebalance(replacement)

    def _remove_leaf(self, node):
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = None
            else:
                node.parent.right = None
            self._rebalance(node.parent)
        else:
            self._tree = None
        node.parent = None
        node.left = None
        node.right = None

    def remove(self, k):
        node = self._get_node(k)
        if not node:
            return
        if AvlTree._is_leaf(node):
            self._remove_leaf(node)
            return
        if node.left and node.right:
            nxt = AvlTree._get_next(node)
            node.key = nxt.key
            node.value = nxt.value
            if self._is_leaf(nxt):
                self._remove_leaf(nxt)
            else:
                self._remove_one(nxt)
            self._rebalance(node)
        else:
            self._remove_one(node)

    def get(self, k):
        node = self._get_node(k)
        return node.value if node else -1

    def _get_node(self, k):
        if not self._tree:
            return None
        node = self._tree
        while node:
            if k < node.key:
                node = node.left
            elif node.key < k:
                node = node.right
            else:
                return node
        return None

    def get_at(self, pos):
        x = pos + 1
        node = self._tree
        while node:
            if x < node.num_left:
                node = node.left
            elif node.num_left < x:
                x -= node.num_left
                node = node.right
            else:
                return (node.key, node.value)
        raise IndexError("Out of ranges")

    @staticmethod
    def _is_left(node):
        return node.parent.left and node.parent.left == node

    @staticmethod
    def _is_leaf(node):
        return node.left is None and node.right is None

    def _rotate_right(self, node):
        if not node.parent:
            self._tree = node.left
            node.left.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.left
            node.left.parent = node.parent
        else:
            node.parent.right = node.left
            node.left.parent = node.parent
        bk = node.left.right
        node.left.right = node
        node.parent = node.left
        node.left = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    def _rotate_left(self, node):
        if not node.parent:
            self._tree = node.right
            node.right.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.right
            node.right.parent = node.parent
        else:
            node.parent.right = node.right
            node.right.parent = node.parent
        bk = node.right.left
        node.right.left = node
        node.parent = node.right
        node.right = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    @staticmethod
    def _get_next(node):
        if not node.right:
            return node.parent
        n = node.right
        while n.left:
            n = n.left
        return n

# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default=300006, func=lambda a, b: min(a , b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b:a + b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m

# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z

# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por

# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left) / 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid] <key):
            count = mid + 1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count

# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c
def binary(x, length):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

def countGreater(arr, n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] > k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)

# --------------------------------------------------binary------------------------------------
class TrieNode:
    def __init__(self):
        self.children = [None] * 26
        self.isEndOfWord = False
class Trie:
    def __init__(self):
        self.root = self.getNode()
    def getNode(self):
        return TrieNode()
    def _charToIndex(self, ch):
        return ord(ch) - ord('a')
    def insert(self, key):
        pCrawl = self.root
        length = len(key)
        for level in range(length):
            index = self._charToIndex(key[level])
            if not pCrawl.children[index]:
                pCrawl.children[index] = self.getNode()
            pCrawl = pCrawl.children[index]
        pCrawl.isEndOfWord = True
    def search(self, key):
        pCrawl = self.root
        length = len(key)
        for level in range(length):
            index = self._charToIndex(key[level])
            if not pCrawl.children[index]:
                return False
            pCrawl = pCrawl.children[index]
        return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
    def __init__(self, data):
        self.data = data
        self.count=0
        self.left = None  # left node for 0
        self.right = None  # right node for 1
class BinaryTrie:
    def __init__(self):
        self.root = Node(0)
    def insert(self, pre_xor):
        self.temp = self.root
        for i in range(31, -1, -1):
            val = pre_xor & (1 << i)
            if val:
                if not self.temp.right:
                    self.temp.right = Node(0)
                self.temp = self.temp.right
                self.temp.count+=1
            if not val:
                if not self.temp.left:
                    self.temp.left = Node(0)
                self.temp = self.temp.left
                self.temp.count += 1
        self.temp.data = pre_xor
    def query(self, xor):
        self.temp = self.root
        for i in range(31, -1, -1):
            val = xor & (1 << i)
            if not val:
                if self.temp.left and self.temp.left.count>0:
                    self.temp = self.temp.left
                elif self.temp.right:
                    self.temp = self.temp.right
            else:
                if self.temp.right and self.temp.right.count>0:
                    self.temp = self.temp.right
                elif self.temp.left:
                    self.temp = self.temp.left
            self.temp.count-=1
        return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
for ik in range(int(input())):
    n,q=map(int,input().split())
    l=list(map(int,input().split()))
    ans=0
    for i in range(n):
        if i==0:
            if l[i]>l[i+1]:
                ans+=l[i]
        elif i==n-1:
            if l[i]>l[i-1]:
                ans+=l[i]
        elif l[i]>l[i-1] and l[i]>l[i+1]:
            ans+=l[i]
        elif l[i]<l[i-1] and l[i]<l[i+1]:
            ans-=l[i]
    print(ans)
    def remove(i,ans):
        if i==0:
            if l[i]>l[i+1]:
                ans-=l[i]
        elif i==n-1:
            if l[i]>l[i-1]:
                ans-=l[i]
        elif l[i]>l[i-1] and l[i]>l[i+1]:
            ans-=l[i]
        elif l[i]<l[i-1] and l[i]<l[i+1]:
            ans+=l[i]
        return ans
    def add(i,ans):
        if i == 0:
            if l[i] > l[i + 1]:
                ans += l[i]
        elif i == n - 1:
            if l[i] > l[i - 1]:
                ans += l[i]
        elif l[i]>l[i-1] and l[i]>l[i+1]:
            ans+=l[i]
        elif l[i]<l[i-1] and l[i]<l[i+1]:
            ans-=l[i]
        return ans
    for j in range(q):
        a,b=map(int,input().split())
        a-=1
        b-=1
        ind=set()
        if a!=0:
            ind.add(a-1)
        if a!=n-1:
            ind.add(a+1)
        ind.add(a)
        if b!=0:
            ind.add(b-1)
        if b!=n-1:
            ind.add(b+1)
        ind.add(b)
        for i in ind:
            ans=remove(i,ans)
        l[a], l[b] = l[b], l[a]
        for i in ind:
            ans = add(i, ans)
        print(ans)


import sys
import math
input = sys.stdin.readline

t = int(input())

for _ in range(t):
    n,q = list(map(int, input().split()))
    arr = list(map(int, input().split()))

    total = 0
    last = 0

    for i in range(n):
        total += max(arr[i] - last, 0)
        last = arr[i]

    arr = [0] + arr + [arr[-1]]
    print(total)

    for _ in range(q):
        x,y = list(map(int, input().split()))
        x_new, y_new = arr[y], arr[x]

        j1, j2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)
        arr[x] = x_new
        arr[-1] = arr[-2]
        n1, n2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)

        total -= j1 + j2
        total += n1 + n2

        j1, j2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)
        arr[y] = y_new
        arr[-1] = arr[-2]
        n1, n2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)

        total -= j1 + j2
        total += n1 + n2
        print(total)


import sys
import math
input = sys.stdin.readline

t = int(input())

for _ in range(t):
    n,q = list(map(int, input().split()))
    arr = list(map(int, input().split()))

    total = 0
    last = 0

    for i in range(n):
        total += max(arr[i] - last, 0)
        last = arr[i]

    arr = [0] + arr
    arr = arr + [arr[-1]]
    print(total)

    for _ in range(q):
        x,y = list(map(int, input().split()))
        x_new, y_new = arr[y], arr[x]

        j1, j2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)
        arr[x] = x_new
        arr[-1] = arr[-2]
        n1, n2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)

        total -= j1 + j2
        total += n1 + n2

        j1, j2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)
        arr[y] = y_new
        arr[-1] = arr[-2]
        n1, n2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)

        total -= j1 + j2
        total += n1 + n2
        print(total)


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

t = int(input())

for _ in range(t):
    n,q = list(map(int, input().split()))
    arr = list(map(int, input().split()))

    total = 0
    last = 0

    for i in range(n):
        total += max(arr[i] - last, 0)
        last = arr[i]

    arr = [0] + arr + [arr[-1]]
    print(total)
    ans = []

    for _ in range(q):
        x,y = list(map(int, input().split()))
        x_new, y_new = arr[y], arr[x]

        j1, j2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)
        arr[x] = x_new
        arr[-1] = arr[-2]
        n1, n2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)

        total -= j1 + j2
        total += n1 + n2

        j1, j2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)
        arr[y] = y_new
        arr[-1] = arr[-2]
        n1, n2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)

        total -= j1 + j2
        total += n1 + n2

        ans.append(str(total))

    print(*ans, sep='\n')


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

t = int(input())

for _ in range(t):
    n,q = list(map(int, input().split()))
    arr = list(map(int, input().split()))

    total = 0
    last = 0

    for i in range(n):
        total += max(arr[i] - last, 0)
        last = arr[i]

    arr = [0] + arr + [arr[-1]]
    print(total)

    for _ in range(q):
        x,y = list(map(int, input().split()))
        x_new, y_new = arr[y], arr[x]

        j1, j2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)
        arr[x] = x_new
        arr[-1] = arr[-2]
        n1, n2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)

        total -= j1 + j2
        total += n1 + n2

        j1, j2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)
        arr[y] = y_new
        arr[-1] = arr[-2]
        n1, n2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)

        total -= j1 + j2
        total += n1 + n2

        print(total)


for _ in range(int(input())):

    n,q=map(int,input().split())
    arr=list(map(int,input().split()))+[0]
    out=0
    for i in range(n):
        out+=max(arr[i]-arr[i-1],0)
    print(out)

    #Queries
    for i in range(q):
        a,b=map(int,input().split())
        a-=1
        b-=1

        #right element will affect two pairs
        out-=max(arr[b+1]-arr[b],0)
        out-=max(arr[b]-arr[b-1],0)

        #left will affect two pairs expect when they are consecutive
        if b!=a+1:
            out-=max(arr[a+1]-arr[a],0)
        out-=max(arr[a]-arr[a-1],0)

        #Swap
        arr[a],arr[b]=arr[b],arr[a]

        #now adding contribution after swap
        #right
        out+=max(arr[b+1]-arr[b],0)
        out+=max(arr[b]-arr[b-1],0)
        #checking consecutiveness
        if b!=a+1:
            out+=max(arr[a+1]-arr[a],0)
        out+=max(arr[a]-arr[a-1],0)

        #Final ans
        print(out)


import sys
input=lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):

    n,q=map(int,input().split())
    arr=list(map(int,input().split()))+[0]
    out=0
    for i in range(n):
        out+=max(arr[i]-arr[i-1],0)
    print(out)

    #Queries
    for i in range(q):
        a,b=map(int,input().split())
        a-=1
        b-=1

        #right element will affect two pairs
        out-=max(arr[b+1]-arr[b],0)
        out-=max(arr[b]-arr[b-1],0)

        #left will affect two pairs expect when they are consecutive
        if b!=a+1:
            out-=max(arr[a+1]-arr[a],0)
        out-=max(arr[a]-arr[a-1],0)

        #Swap
        arr[a],arr[b]=arr[b],arr[a]

        #now adding contribution after swap
        #right
        out+=max(arr[b+1]-arr[b],0)
        out+=max(arr[b]-arr[b-1],0)
        #checking consecutiveness
        if b!=a+1:
            out+=max(arr[a+1]-arr[a],0)
        out+=max(arr[a]-arr[a-1],0)

        #Final ans
        print(out)


#Fast I/O
import sys,os
import math
# To enable the file I/O i the below 2 lines are uncommented.
# read from in.txt if uncommented
if os.path.exists('in.txt'): sys.stdin=open('in.txt','r')
# will print on Console if file I/O is not activated
#if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w')

# inputs template
from io import BytesIO, IOBase

def main():
    pass

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

#for array of integers
def MI():return (map(int,input().split()))
# endregion
#for fast output, always take string
def out(var): sys.stdout.write(str(var)+'\n')
# end of any user-defined functions

# main functions for execution of the program.
if __name__ == '__main__':
    #This doesn't works here but works wonders when submitted on CodeChef or CodeForces
    for _ in range(int(input())):

        n,q=map(int,input().split())
        arr=list(map(int,input().split()))+[0]
        out=0
        for i in range(n):
            out+=max(arr[i]-arr[i-1],0)
        print(out)

        #Queries
        for i in range(q):
            a,b=map(int,input().split())
            a-=1
            b-=1

            #right element will affect two pairs
            out-=max(arr[b+1]-arr[b],0)
            out-=max(arr[b]-arr[b-1],0)

            #left will affect two pairs expect when they are consecutive
            if b!=a+1:
                out-=max(arr[a+1]-arr[a],0)
            out-=max(arr[a]-arr[a-1],0)

            #Swap
            arr[a],arr[b]=arr[b],arr[a]

            #now adding contribution after swap
            #right
            out+=max(arr[b+1]-arr[b],0)
            out+=max(arr[b]-arr[b-1],0)
            #checking consecutiveness
            if b!=a+1:
                out+=max(arr[a+1]-arr[a],0)
            out+=max(arr[a]-arr[a-1],0)

            #Final ans
            print(out)


#include<bits/stdc++.h>
#include<math.h>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<vector>
#include<string>
#define MAXN 100001
#define Endl '\n'
#define pb push_back
#define mp make_pair
#define lb lower_bound
#define up  upper_bound
#define ll long long int
#define pii pair<ll,ll>
#define all(v) v.begin(),v.end()
#define fi(x,n) for(ll i=x;i<n;i++)
#define fj(x,n) for(ll j=x;j<n;j++)
#define fk(x,n) for(ll k=x;k<n;k++)
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
ll gcd(ll a,ll b){if(b==0)return a;return gcd(b,a%b);}
ll exp(ll x,ll y,ll mod)
{
	ll res=1;
	x=x%mod;
	while(y>0)
	{
		if(y&1)
			res=(res*x)%mod;
		y = y>>1;
		x=(x*x)%mod;
	}
	return res;
}
ll modinverse(ll x,ll mod)
{
    return exp(x,mod-2,mod);
}
using namespace std;
const ll inf = 0x3f3f3f3f3f3f3f3fll;
ll dp[26][26];
int main()
{
    fastio;
    ll n;
    cin>>n;
    vector <ll> ans;
    string s;
    cin>>s;

    ll x,y,res=0;
    fi(0,n)
    {
        x=s[i]-'0';
        res=0;
        fj(i+1,n)
        {
            if((s[j]-'0')>=x)
                y=(s[j]-'0')-x;
            else
                y=10-(x-(s[j]-'0'));

            res=res*10+y;
        }

        fj(0,i)
        {
            if((s[j]-'0')>=x)
                y=(s[j]-'0')-x;
            else
                y=10-(x-(s[j]-'0'));

            res=res*10+y;
        }
        ans.pb(res);
    }
    res=*min_element(all(ans));

    ll d=(ll)log10(res)+1;
    fi(0,n-d)
        cout<<0;
    cout<<res;

    return 0;
}