
You are given an array of N integers. Your task is to find the sum of all elements that appear before the original last element in the sorted version of the array.
The process is as follows:
1) Identify the value of the last element in the original, unsorted array. Let's call this the target_element.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 array.
Print a single integer representing the calculated sum.
If the input array has fewer than 2 elements, there are no elements before the last one, so the sum is 0.
The sum can be large, so be sure to use a data type that can accommodate it (e.g., long in Java, long long in C++).
8
3 1 4 1 5 9 2 6
16
1. The original last element is `6`.
2. The sorted array is `[1, 1, 2, 3, 4, 5, 6, 9]`.
3. The first (and only) occurrence of `6` is at index 6.
4. The sum of elements before index 6 is `1 + 1 + 2 + 3 + 4 + 5 = 16`.
4
10 30 20 5
0
1. The original last element is `5`.
2. The sorted array is `[5, 10, 20, 30]`.
3. The first occurrence of `5` is at index 0.
4. There are no elements before index 0, so the sum is 0.
The expected time complexity is O(N log N).
1 <= N <= 10^5
-10^9 <= arr[i] <= 10^9
Time limit: 1 sec