The Naive Approach
For every $$$W_k$$$ (out of $$$M$$$ options), we add it to $$$H$$$, sort the $$$N+1$$$ elements, and calculate the cost. Time Complexity: $$$O(M \cdot N \log N)$$$. Given $$$N, M \le 2 \times 10^5$$$, this will result in Time Limit Exceeded (TLE). We need a faster way to evaluate each $$$W_k$$$
The Optimization
Instead of sorting from scratch every time, we can sort the array $$$H$$$ once at the beginning. Because $$$H$$$ is sorted, we can use Binary Search (like lower_bound in C++) to find the exact position where $$$W_k$$$ would be inserted in $$$O(\log N)$$$ time.Let $$$idx$$$ be the index where $$$W_k$$$ is inserted (i.e., the number of elements in $$$H$$$ strictly less than $$$W_k$$$).
adding $$$W_k$$$ affects the pairing of the already sorted elements in $$$H$$$.
The array splits into three parts:
- Elements before $$$W_k$$$
- $$$W_k$$$ itself paired with one adjacent element.
- Elements after $$$W_k$$$
the pairing depends on whether the insertion index $$$idx$$$ is even or odd (assuming 0-based indexing for array $$$H$$$).
Case 1: $$$idx$$$ is even
There is an even number of elements before $$$W_k$$$. This means they pair up perfectly with each other.$$$W_k$$$ will end up at an even index, so it must pair with the element immediately after it (which is $$$H[idx]$$$).
The elements after $$$H[idx]$$$ will also pair up perfectly among themselves.
Cost formula: (Cost of pairing $$$H[0 \dots idx-1]$$$) + $$$(H[idx] - W_k)$$$ + (Cost of pairing $$$H[idx+1 \dots N-1]$$$).
Case 2: $$$idx$$$ is odd
There is an odd number of elements before $$$W_k$$$. The elements $$$H[0 \dots idx-2]$$$ pair perfectly.The leftover element $$$H[idx-1]$$$ will pair with $$$W_k$$$.The remaining elements after $$$W_k$$$ ($$$H[idx \dots N-1]$$$) will pair up perfectly among themselves.
Cost formula: (Cost of pairing $$$H[0 \dots idx-2]$$$) + $$$(W_k - H[idx-1])$$$ + (Cost of pairing $$$H[idx \dots N-1]$$$).
To make the formulas above $$$O(1)$$$ after finding the index, we can use Prefix and Suffix arrays for the pairing costs.
- pref[i]: Cost of pairing the prefix up to index $$$i-1$$$ (where $$$i$$$ is even).
$$$pref[i] = pref[i-2] + (H[i-1] - H[i-2])$$$ - suff[i]: Cost of pairing the suffix starting from index $$$i$$$ (where $$$N-i$$$ is even).
$$$suff[i] = suff[i+2] + (H[i+1] - H[i])$$$Time Complexity: $$$O(N \log N)$$$ to sort $$$H$$$, $$$O(N)$$$ to build prefix/suffix arrays, and $$$O(M \log N)$$$ to binary search for every $$$W_k$$$.
Total: $$$\mathcal{O}((N + M) \log N)$$$.