Let S0 be the value before the operation. Suppose Ax,k=a and Bk,x=b are swapped, and let d=b−a. Then Ax,k increases by d, while Bk,x decreases by d.
Among the entries included in S, the total change strictly to the right of the diagonal in row x is
dj=x+1∑NBk,j,
and the total change strictly above the diagonal in column x is
−di=1∑x−1Ai,k.
The diagonal entry does not change because the affected product Ax,kBk,x=ab becomes . Hence,
Δx,k=(B
Define column prefix sums of A and row suffix sums of B by
Pi,k=r=1
With P0,k=0 and Qk,N+1, each change is computed in as
Δx,k=(Bk
The initial sum can also be computed without constructing the entire product by changing the order of summation:
S0=i=1∑N
Since performing no operation is allowed, the answer is
S0+max(0,1≤x,k≤
Both the time and space complexities are O(N2).
Solution written by GPT6