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

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 Arrayconst int maxn = 1000000;Â
// Function to find the sum of previous// numbers that are greater than the// current number for the given arrayvoid 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 Codeint 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;} |
Java
// Java program for the above approachclass GFG{Â
// Max Element of the Arraystatic int maxn = 1000000;Â
// Function to find the sum of previous// numbers that are greater than the// current number for the given arraystatic 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        System.out.print(cur_sum + " ");    }}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â Â Â Â Â Â // Given array arr[]Â Â Â Â int ar[] = { 7, 3, 6, 2, 1 };Â
    // Size of the array    int N = ar.length;Â
    // Function call    sumGreater(ar, N);}}Â
// This code is contributed by amal kumar choubey |
Python3
# Python3 program for the above approachÂ
# Max Element of the Arraymaxn = 1000000;Â
# Function to find the sum of previous# numbers that are greater than the# current number for the given arraydef sumGreater(ar, N):Â
    # Loop to iterate over all    # the elements of the array    for i in range(N):Â
        # Store the answer for        # the current element        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 j in range(i, -1, -1):            if (ar[j] > ar[i]):                cur_sum += ar[j];                 # Print the answer for        # current element        print(cur_sum, end = " ");     # Driver Codeif __name__ == '__main__':Â
    # Given array arr    ar = [ 7, 3, 6, 2, 1] ;Â
    # Size of the array    N = len(ar);Â
    # Function call    sumGreater(ar, N);Â
# This code is contributed by sapnasingh4991 |
C#
// C# program for the above approachusing System;Â
class GFG{Â
// Max Element of the Array//static int maxn = 1000000;Â
// Function to find the sum of previous// numbers that are greater than the// current number for the given arraystatic 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        Console.Write(cur_sum + " ");    }}Â
// Driver Codepublic static void Main(String[] args){         // Given array []arr    int []ar = { 7, 3, 6, 2, 1 };Â
    // Size of the array    int N = ar.Length;Â
    // Function call    sumGreater(ar, N);}}Â
// This code is contributed by Amit Katiyar |
Javascript
<script>Â
// Javascript program for the above approach   // Max Element of the Arrayvar maxn = 1000000;Â
// Function to find the sum of previous// numbers that are greater than the// current number for the given arrayfunction sumGreater(ar, N){         // Loop to iterate over all    // the elements of the array    for(i = 0; i < N; i++)     {                 // Store the answer for        // the current element        var 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(j = i - 1; j >= 0; j--)         {            if (ar[j] > ar[i])                cur_sum += ar[j];        }Â
        // Print the answer for        // current element        document.write(cur_sum + " ");    }}Â
// Driver CodeÂ
// Given array arrvar ar = [ 7, 3, 6, 2, 1 ];Â
// Size of the arrayvar N = ar.length;Â
// Function callsumGreater(ar, N);Â
// This code is contributed by umadevi9616Â
</script> |
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:
- Traverse the given array and find the sum(say total_sum) of all the elements stored in the Fenwick Tree.
- Now Consider each element(say arr[i]) as the index of the Fenwick Tree.
- Now find the sum of all the elements(say curr_sum) which is smaller than the current element using values stored in Tree.
- 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.
- Update the current element in the Fenwick Tree.
- Repeat the above steps for all the elements in the array.
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 Arrayconst int maxn = 1000000;Â
// Initializing Fenwick Treeint Bit[maxn + 5];Â
// Function to calculate the sum of// previous numbers that are greater// than the current number in the arrayvoid sum(int ar[], int N){Â
    // Iterate from 1 to N    for (int i = 0; i < N; i++) {        int index;        int total_sum = 0;        index = 100000;Â
        // If some greater values has        // occurred before current element        // then it will be already stored        // in Fenwick Tree        while (index) {Â
            // Calculating sum of            // all the elements            total_sum += Bit[index];            index -= index & -index;        }        int cur_sum = 0;Â
        // Sum only smaller or equal        // elements than current element        index = ar[i];Â
        while (index) {Â
            // If some smaller values has            // occurred before it will be            // already stored in Tree            cur_sum += Bit[index];            index -= (index & -index);        }Â
        int ans = total_sum - cur_sum;        cout << ans << " ";Â
        // Update the fenwick tree        index = ar[i];        while (index <= 100000) {Â
            // Updating The Fenwick Tree            // for future values            Bit[index] += ar[i];            index += (index & -index);        }    }}Â
// Driver Codeint main(){Â Â Â Â // Given array arr[]Â Â Â Â int ar[] = { 7, 3, 6, 2, 1 };Â Â Â Â int N = sizeof ar / sizeof ar[0];Â
    // Function call    sum(ar, N);    return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{Â
// Max Element of the Arraystatic int maxn = 1000000;Â
// Initializing Fenwick Treestatic int []Bit = new int[maxn + 5];Â
// Function to calculate the sum of// previous numbers that are greater// than the current number in the arraystatic void sum(int ar[], int N){Â
    // Iterate from 1 to N    for (int i = 0; i < N; i++)     {        int index;        int total_sum = 0;        index = 100000;Â
        // If some greater values has        // occurred before current element        // then it will be already stored        // in Fenwick Tree        while (index > 0)        {Â
            // Calculating sum of            // all the elements            total_sum += Bit[index];            index -= index & -index;        }        int cur_sum = 0;Â
        // Sum only smaller or equal        // elements than current element        index = ar[i];Â
        while (index > 0)        {Â
            // If some smaller values has            // occurred before it will be            // already stored in Tree            cur_sum += Bit[index];            index -= (index & -index);        }Â
        int ans = total_sum - cur_sum;        System.out.print(ans + " ");Â
        // Update the fenwick tree        index = ar[i];        while (index <= 100000)         {Â
            // Updating The Fenwick Tree            // for future values            Bit[index] += ar[i];            index += (index & -index);        }    }}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â // Given array arr[]Â Â Â Â int ar[] = { 7, 3, 6, 2, 1 };Â Â Â Â int N = ar.length;Â
    // Function call    sum(ar, N);}}Â
// This code is contributed by Rohit_ranjan |
Python3
# Python3 program for the above approachÂ
# Max Element of the Arraymaxn = 1000000;Â
# Initializing Fenwick TreeBit = [0] * (maxn + 5);Â
# Function to calculate the sum of# previous numbers that are greater# than the current number in the arraydef sum(ar, N):Â Â Â Â Â Â Â # Iterate from 1 to NÂ Â Â Â for i in range(N):Â Â Â Â Â Â Â Â total_sum = 0;Â Â Â Â Â Â Â Â index = 100000;Â
        # If some greater values has        # occurred before current element        # then it will be already stored        # in Fenwick Tree        while (index > 0):                       # Calculating sum of            # all the elements            total_sum += Bit[index];            index -= index & -index;Â
        cur_sum = 0;Â
        # Sum only smaller or equal        # elements than current element        index = ar[i];Â
        while (index > 0):                       # If some smaller values has            # occurred before it will be            # already stored in Tree            cur_sum += Bit[index];            index -= (index & -index);Â
        ans = total_sum - cur_sum;        print(ans, end=" ");Â
        # Update the fenwick tree        index = ar[i];        while (index <= 100000):                       # Updating The Fenwick Tree            # for future values            Bit[index] += ar[i];            index += (index & -index);Â
# Driver Codeif __name__ == '__main__':    # Given array arr    arr = [7, 3, 6, 2, 1];    N = len(arr);Â
    # Function call    sum(arr, N);Â
# This code is contributed by sapnasingh4991 |
C#
// C# program for the above approachusing System;class GFG{Â
// Max Element of the Arraystatic int maxn = 1000000;Â
// Initializing Fenwick Treestatic int []Bit = new int[maxn + 5];Â
// Function to calculate the sum of// previous numbers that are greater// than the current number in the arraystatic void sum(int []ar, int N){Â
    // Iterate from 1 to N    for (int i = 0; i < N; i++)     {        int index;        int total_sum = 0;        index = 100000;Â
        // If some greater values has        // occurred before current element        // then it will be already stored        // in Fenwick Tree        while (index > 0)        {Â
            // Calculating sum of            // all the elements            total_sum += Bit[index];            index -= index & -index;        }        int cur_sum = 0;Â
        // Sum only smaller or equal        // elements than current element        index = ar[i];Â
        while (index > 0)        {Â
            // If some smaller values has            // occurred before it will be            // already stored in Tree            cur_sum += Bit[index];            index -= (index & -index);        }Â
        int ans = total_sum - cur_sum;        Console.Write(ans + " ");Â
        // Update the fenwick tree        index = ar[i];        while (index <= 100000)         {Â
            // Updating The Fenwick Tree            // for future values            Bit[index] += ar[i];            index += (index & -index);        }    }}Â
// Driver Codepublic static void Main(String[] args){    // Given array []arr    int []ar = { 7, 3, 6, 2, 1 };    int N = ar.Length;Â
    // Function call    sum(ar, N);}}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>// javascript program for the above approachÂ
    // Max Element of the Array    var maxn = 1000000;Â
    // Initializing Fenwick Tree     var Bit = Array(maxn + 5).fill(0);Â
    // Function to calculate the sum of    // previous numbers that are greater    // than the current number in the array    function sum(ar , N) {Â
        // Iterate from 1 to N        for (i = 0; i < N; i++) {            var index;            var total_sum = 0;            index = 100000;Â
            // If some greater values has            // occurred before current element            // then it will be already stored            // in Fenwick Tree            while (index > 0) {Â
                // Calculating sum of                // all the elements                total_sum += Bit[index];                index -= index & -index;            }            var cur_sum = 0;Â
            // Sum only smaller or equal            // elements than current element            index = ar[i];Â
            while (index > 0) {Â
                // If some smaller values has                // occurred before it will be                // already stored in Tree                cur_sum += Bit[index];                index -= (index & -index);            }Â
            var ans = total_sum - cur_sum;            document.write(ans + " ");Â
            // Update the fenwick tree            index = ar[i];            while (index <= 100000) {Â
                // Updating The Fenwick Tree                // for future values                Bit[index] += ar[i];                index += (index & -index);            }        }    }Â
    // Driver Code             // Given array arr        var ar = [ 7, 3, 6, 2, 1 ];        var N = ar.length;Â
        // Function call        sum(ar, N);Â
// This code contributed by aashish1995</script> |
0 7 7 16 18
Â
Time Complexity: O(N * log(max_element))
Auxiliary Space: O(max_element)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!


