TLDR:
You're looking for the number of inversions in the array for descending sorting. This is doable in O(n lg n)
.
The number of inversions in an array A
is defined as the number of all pairs of indices i
, j
, such that i < j
and A[i] > A[j]
. So basically the number of pairs of values in A
such that the first would appear after the second, if A
was sorted. This can be calculated by going through all values in A
and counting preceding values that should come afterwards:
count_inversions(A):
count = 0
for i=0 to length of A - 1:
for j=0 to i - 1:
if A[i] > A[j]:
count++
return count
For your problem the naive solution would be quite similar:
total_delete_cost(A):
count = 0
for i=0 to length of A - 1:
for j=0 to i - 1:
if A[i] < A[j]:
count++
return count
The only thing that changed is the line if A[i] > A[j]
. Or looking at it another way: each value x
in A
will add m
to the total cost, where m
is the number of values that are larger than x
and have a higher index. This is precisely the number of inversions for a reverse ordering from A
.
From here on the remainder of the question is answered here, except for the minor adaption to switch from ascending to descending ordering, so I won't post the code to solve the remainder of the problem.