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:

  • C++

// C++ program for the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Max Element of the Array

**const** **int** maxn = 1000000;

// Function to find the sum of previous

// numbers that are greater than the

// current number for the given array

**void** sumGreater(``**int** ar[], **int** N)

{

// Loop to iterate over all

// the elements of the array

**for** (``**int** i = 0; i < N; i++) {

// Store the answer for

// the current element

**int** cur_sum = 0;

// Iterate from (current index - 1)

// to 0 and check if ar[j] is greater

// than the current element and add

// it to the cur_sum if so

**for** (``**int** j = i - 1; j >= 0; j--) {

**if** (ar[j] > ar[i])

cur_sum += ar[j];

}

// Print the answer for

// current element

cout << cur_sum << " "``;

}

}

// Driver Code

**int** main()

{

// Given array arr[]

**int** ar[] = { 7, 3, 6, 2, 1 };

// Size of the array

**int** N = **sizeof** ar / **sizeof** ar[0];

// Function call

sumGreater(ar, N);

**return** 0;

}

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.

#arrays #competitive programming #tree #binary indexed tree #bit #segment-tree

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