VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-of-previous-numbers-that-are-greater-than-current-number-for-given-array/

⇱ Sum of previous numbers that are greater than current number for given array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of previous numbers that are greater than current number for given array

Last Updated : 15 Jul, 2025

Given an array A[], for each element in the array, the task is to find the sum of all the previous elements which are strictly greater than the current element.

Examples:

Input: A[] = {2, 6, 4, 1, 7}
Output: 0 0 6 12 0
Explanation: 
For 2 and 6 there is no element greater to it on the left.
For 4 there is 6.
For 1 the sum would be 12.
For 7 there is again no element greater to it.

Input: A[] = {7, 3, 6, 2, 1}
Output: 0 7 7 16 18
Explanation: 
For 7 there is no element greater to it on the left. 
For 3 there is 7.
For 6 the sum would be 7.
For 2 it has to be 7 + 3 + 6 = 16.
For 1 the sum would be 7 + 3 + 6 + 2 = 18

Naive Approach: For each element, the idea is to find the elements which are strictly greater than the current element on the left side of it and then find the sum of all those elements.

Below is the implementation of the above approach:


Output: 
0 7 7 16 18

 

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach the idea is to use Fenwick Tree. Below are the steps:

  1. Traverse the given array and find the sum(say total_sum) of all the elements stored in the Fenwick Tree.
  2. Now Consider each element(say arr[i]) as the index of the Fenwick Tree.
  3. Now find the sum of all the elements(say curr_sum) which is smaller than the current element using values stored in Tree.
  4. The value of total_sum - curr_sum will give the sum of all elements which are strictly greater than the elements on the left side of the current element.
  5. Update the current element in the Fenwick Tree.
  6. Repeat the above steps for all the elements in the array.

Below is the implementation of the above approach:


Output: 
0 7 7 16 18

 

Time Complexity: O(N * log(max_element))
Auxiliary Space: O(max_element)


 

Comment
Article Tags: