
You are given an array charge of size n, where charge[i] represents the charge value of a system.
You must remove all systems one by one until only a single system remains. The goal is to perform these removals in an order that maximizes the charge of this final remaining system.
The operation is defined as follows:
Your task is to find the maximum possible charge of the final system.
The first line of input contains an integer 'N', the size of the array.
The second line contains 'N' space-separated integers, representing the elements of the charge array.
Print a single integer representing the maximum possible charge of the final system.
A simple greedy approach does not work. The optimal strategy often involves removing elements that result in a smaller immediate merge cost to set up a larger merge later.
4
3 2 4 5
51
We can form the following three pairs:
1. (10, 5) since 10 > 5
2. (20, 15) since 20 > 15
3. (30, 25) since 30 > 25
All elements are used, and we have a total of 3 pairs, which is the maximum possible.
4
1 2 8 9
3 4 5 6
2
The optimal way to form pairs is:
1. (8, 3) since 8 > 3
2. (9, 4) since 9 > 4
The elements 1 and 2 from array 'a' cannot be paired with any remaining elements from array 'b' (5 and 6). The maximum number of pairs is 2.
The expected time complexity is O(n log n).
1 <= n <= 10^5
-10^9 <= a[i], b[i] <= 10^9
Time limit: 1 sec