Last Updated: 30 Sep, 2025

Sorted Predecessor Sum

Easy
Asked in company
Tricon Infotech Pvt Ltd

Problem statement

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.


2) Sort the entire array in non-decreasing (ascending) order.


3) In the newly sorted array, find the index of the first occurrence of the target_element.


4) Calculate and return the sum of all elements that appear at indices before this index. If the target_element is the first element in the sorted array, this sum will be 0.


Input Format:
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.


Output Format:
Print a single integer representing the calculated sum.


Note:
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++).