Open In App

Find the Alpha Score of the Given Steps (Using BST)

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] consisting of N numbers denoting the values written on N steps, the task is to find the alpha score of the total journey of climbing up all the stairs. Since the answer can be very large, print the answer modulo 109 + 7.

Alpha Score: The alpha score at each step is the sum of all the numbers previously seen on the stairs climbed which are smaller than the number on the current stair.
The alpha score of the total journey is the sum of the alpha scores of each step.

Examples: 

Input: A[] = {13, 14, 20}
Output: 87
Explanation:
Alpha Score at the first stair = 13
Alpha Score at the second stair = 13 + 14 = 27
Alpha Score of the third stair = 13 + 14 + 20 = 47          
Sum of all the Alpha Scores=13 + 27 + 47 = 87
Therefore, the Alpha Score of the total journey is 87.

Input: A[] = {10, 11, 12} 
Output: 64
Explanation: 
Alpha Score at the first stair = 10
Alpha Score at the second stair = 10 + 11 = 21
Alpha Score of the third stair = 10+11 + 12 = 33  
Sum of all the Alpha Scores =10 + 21 + 33
Therefore, the Alpha Score of the total journey is 64.

Naive Approach: 
The simplest approach to solve the problem is to traverse each element in the array and calculate the sum of all the elements smaller than the current element present at previous indices to calculate the Alpha Score of the current stair. For each sum calculated, update the total_sum(Alpha Score of the total journey). Finally, print the total_sum as the Alpha Score of the complete journey.

Below is the implementation of the approach:

C++




// C++ code for the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the alpha score
int findAlphaScore(int A[], int n) {
    int mod = 1e9 + 7; // Define the modulo value
    int total_sum = 0; // Initialize the total alpha score to 0
 
    // Traverse each element in the array
    for (int i = 0; i < n; i++) {
        int sum = A[i]; // Initialize the sum for each element to A[i]
 
        // Calculate the sum of all the elements smaller than the current element
        for (int j = 0; j < i; j++) {
            if (A[j] < A[i]) {
                sum = (sum + A[j]) % mod;
            }
        }
 
        // Update the total alpha score
        total_sum = (total_sum + sum) % mod;
    }
 
    // Return the total alpha score
    return total_sum;
}
 
// Driver code
int main() {
    int A[] = { 10, 11, 12 }; // Given array
    int n = sizeof(A) / sizeof(A[0]); // Calculate size of array
 
    // Function call to find alpha score
    int alphaScore = findAlphaScore(A, n);
 
    // Print the alpha score
    cout << alphaScore << endl;
 
    return 0;
}


Java




// Java code for the approach
 
import java.util.*;
 
public class GFG {
    // Function to find the alpha score
    public static int findAlphaScore(int A[], int n)
    {
        int mod = 1000000007; // Define the modulo value
        int total_sum
            = 0; // Initialize the total alpha score to 0
                 // Traverse each element in the array
        for (int i = 0; i < n; i++) {
            int sum = A[i]; // Initialize the sum for each
                            // element to A[i]
 
            // Calculate the sum of all the elements smaller
            // than the current element
            for (int j = 0; j < i; j++) {
                if (A[j] < A[i]) {
                    sum = (sum + A[j]) % mod;
                }
            }
 
            // Update the total alpha score
            total_sum = (total_sum + sum) % mod;
        }
 
        // Return the total alpha score
        return total_sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int A[] = { 10, 11, 12 }; // Given array
        int n = A.length; // Calculate size of array
 
        // Function call to find alpha score
        int alphaScore = findAlphaScore(A, n);
 
        // Print the alpha score
        System.out.println(alphaScore);
    }
}


Python3




def find_alpha_score(arr):
    mod = 10**9 + 7 # Define the modulo value
    total_sum = 0 # Initialize the total alpha score to 0
 
    # Traverse each element in the array
    for i in range(len(arr)):
        s = arr[i] # Initialize the sum for each element to A[i]
 
        # Calculate the sum of all the elements smaller than the current element
        for j in range(i):
            if arr[j] < arr[i]:
                s = (s + arr[j]) % mod
 
        # Update the total alpha score
        total_sum = (total_sum + s) % mod
 
    # Return the total alpha score
    return total_sum
 
# Driver code
arr = [10, 11, 12] # Given array
alpha_score = find_alpha_score(arr)
 
# Print the alpha score
print(alpha_score)


C#




using System;
 
public class MainClass {
    public static long FindAlphaScore(int[] arr) {
        
        // Define the modulo value
        int mod = 1000000007;
         
        // Initialize the total alpha score to 0
        long totalSum = 0;
         
        // Traverse each element in the array
        for (int i = 0; i < arr.Length; i++) {
             
            // Initialize the sum for each element to A[i]
            int s = arr[i];
             
             // Calculate the sum of all the elements smaller
            // than the current element
            for (int j = 0; j < i; j++) {
                if (arr[j] < arr[i]) {
                    s = (s + arr[j]) % mod;
                }
            }
             
            // Update the total alpha score
            totalSum = (totalSum + s) % mod;
        }
         
        // Return the total alpha score
        return totalSum;
    }
 
    // Driver code
    public static void Main(string[] args) {
        int[] arr = { 10, 11, 12 };
        long alphaScore = FindAlphaScore(arr);
         
        // Print the alpha score
        Console.WriteLine(alphaScore);
    }
}
// This code is contributed by shiv1o43g


Javascript




function findAlphaScore(arr) {
  const mod = 1000000007;
  let totalSum = 0;
  for (let i = 0; i < arr.length; i++) {
    let s = arr[i];
    for (let j = 0; j < i; j++) {
      if (arr[j] < arr[i]) {
        s = (s + arr[j]) % mod;
      }
    }
    totalSum = (totalSum + s) % mod;
  }
  return totalSum;
}
 
const arr = [10, 11, 12];
const alphaScore = findAlphaScore(arr);
console.log(alphaScore);


Output

64

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

Efficient Approach: 
The above approach can be optimized using Binary Search Trees. Follow the steps below:

  • Sort the given array.
  • Construct a BST from the sorted array.
  • Recursively traverse the BST and follow the steps below:
    • Traverse the left subtree.
    • Add the value of the current node to sum (Alpha score for current stair) and update the total_sum (Alpha score of the journey till now).
    • Traverse the right subtree.
  • After complete traversal of the BST, print the total_sum.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
 
static long sum = 0, total_sum = 0;
static long mod = 1000000007;
 
// Structure of a node
struct Node
{
    Node *left, *right;
    int data;
     
    Node(int x)
    {
        data = x;
        left = NULL;
        right = NULL;
    }
};
 
// Function to calculate and return
// the Alpha Score of the journey
long getAlphaScore(Node* node)
{
     
    // Traverse left subtree
    if (node->left != NULL)
        getAlphaScore(node->left);
 
    // Calculate the alpha score
    // of the current step
    sum = (sum + node->data) % mod;
 
    // Update alpha score of
    // the journey
    total_sum = (total_sum + sum) % mod;
 
    // Traverse right subtree
    if (node->right != NULL)
        getAlphaScore(node->right);
 
    // Return
    return total_sum;
}
 
// Function to construct a BST
// from the sorted array arr[]
Node* constructBST(int arr[], int start,
                   int end, Node* root)
{
    if (start > end)
        return NULL;
 
    int mid = (start + end) / 2;
 
    // Insert root
    if (root == NULL)
        root = new Node(arr[mid]);
 
    // Construct left subtree
    root->left = constructBST(arr, start,
                              mid - 1, root->left);
 
    // Construct right subtree
    root->right = constructBST(arr, mid + 1, end,
                               root->right);
 
    // Return root
    return root;
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 11, 12 };
    int length = 3;
     
    // Sort the array
    sort(arr, arr + length);
     
    Node *root = NULL;
     
    // Construct BST from the sorted array
    root = constructBST(arr, 0, length - 1, root);
     
    cout << (getAlphaScore(root));
}
 
// This code is contributed by mohit kumar 29


Java




// Java Program to implement
// the above approach
import java.lang.*;
import java.util.*;
 
// Structure of a node
class Node {
    Node left, right;
    int data;
    public Node(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }
}
 
class AlphaScore {
 
    Node root;
 
    AlphaScore() { root = null; }
 
    static long sum = 0, total_sum = 0;
    static long mod = 1000000007;
 
    // Function to calculate and return
    // the Alpha Score of the journey
    public static long getAlphaScore(Node node)
    {
        // Traverse left subtree
        if (node.left != null)
            getAlphaScore(node.left);
 
        // Calculate the alpha score
        // of the current step
        sum = (sum + node.data) % mod;
 
        // Update alpha score of
        // the journey
        total_sum = (total_sum + sum) % mod;
 
        // Traverse right subtree
        if (node.right != null)
            getAlphaScore(node.right);
 
        // Return
        return total_sum;
    }
 
    // Function to construct a BST
    // from the sorted array arr[]
    public static Node constructBST(int[] arr, int start,
                                    int end, Node root)
    {
        if (start > end)
            return null;
 
        int mid = (start + end) / 2;
 
        // Insert root
        if (root == null)
            root = new Node(arr[mid]);
 
        // Construct left subtree
        root.left
            = constructBST(arr, start, mid - 1, root.left);
 
        // Construct right subtree
        root.right
            = constructBST(arr, mid + 1, end, root.right);
 
        // Return root
        return root;
    }
 
    // Driver Code
    public static void main(String args[])
    {
 
        int arr[] = { 10, 11, 12 };
        int length = arr.length;
 
        // Sort the array
        Arrays.sort(arr);
 
        Node root = null;
 
        // Construct BST from the sorted array
        root = constructBST(arr, 0, length - 1, root);
 
        System.out.println(getAlphaScore(root));
    }
}


Python3




# Python3 program to implement
# the above approach
 
# Structure of a node
class Node:
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
         
sum = 0
total_sum = 0
mod = 1000000007
     
# Function to calculate and return
# the Alpha Score of the journey
def getAlphaScore(node):
     
    global sum
    global total_sum
     
    # Traverse left subtree
    if node.left != None:
        getAlphaScore(node.left)
         
    # Calculate the alpha score
    # of the current step
    sum = (sum + node.data) % mod
     
    # Update alpha score of
    # the journey
    total_sum = (total_sum + sum) % mod
     
    # Traverse right subtree
    if node.right != None:
        getAlphaScore(node.right)
         
    # Return
    return total_sum
 
# Function to construct a BST
# from the sorted array arr[]
def constructBST(arr, start, end, root):
     
    if start > end:
        return None
     
    mid = (start + end) // 2
     
    # Insert root
    if root == None:
        root = Node(arr[mid])
         
    # Construct left subtree
    root.left = constructBST(arr, start,
                             mid - 1,
                             root.left)
     
    # Construct right subtree
    root.right = constructBST(arr, mid + 1,
                              end, root.right)
     
    # Return root
    return root
 
# Driver code
arr = [ 10, 11, 12 ]
length = len(arr)
 
# Sort the array
arr.sort()
 
root = None
 
# Construct BST from the sorted array
root = constructBST(arr, 0, length - 1, root)
 
print(getAlphaScore(root))
 
# This code is contributed by Shivam Singh


C#




// C# program to implement
// the above approach
using System;
 
// Structure of a node
class Node
{
    public Node left, right;
    public int data;
    public Node(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }
}
 
class AlphaScore{
 
Node root;
 
AlphaScore(){root = null;}
 
static long sum = 0, total_sum = 0;
static long mod = 1000000007;
 
// Function to calculate and return
// the Alpha Score of the journey
static long getAlphaScore(Node node)
{
     
    // Traverse left subtree
    if (node.left != null)
        getAlphaScore(node.left);
 
    // Calculate the alpha score
    // of the current step
    sum = (sum + node.data) % mod;
 
    // Update alpha score of
    // the journey
    total_sum = (total_sum + sum) % mod;
 
    // Traverse right subtree
    if (node.right != null)
        getAlphaScore(node.right);
 
    // Return
    return total_sum;
}
 
// Function to construct a BST
// from the sorted array []arr
static Node constructBST(int[] arr, int start,
                         int end, Node root)
{
    if (start > end)
        return null;
 
    int mid = (start + end) / 2;
 
    // Insert root
    if (root == null)
        root = new Node(arr[mid]);
 
    // Construct left subtree
    root.left = constructBST(arr, start,
                             mid - 1, root.left);
 
    // Construct right subtree
    root.right = constructBST(arr, mid + 1,
                              end, root.right);
 
    // Return root
    return root;
}
 
// Driver Code
public static void Main(String []args)
{
 
    int []arr = { 10, 11, 12 };
    int length = arr.Length;
 
    // Sort the array
    Array.Sort(arr);
 
    Node root = null;
 
    // Construct BST from the sorted array
    root = constructBST(arr, 0, length - 1, root);
 
    Console.WriteLine(getAlphaScore(root));
}
}
 
// This is code contributed by PrinciRaj1992


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Structure of a node
class Node
{
    constructor(data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
 
var root = null;
 
function AlphaScore(){root = null;}
 
var sum = 0, total_sum = 0;
var mod = 1000000007;
 
// Function to calculate and return
// the Alpha Score of the journey
function getAlphaScore(node)
{
     
    // Traverse left subtree
    if (node.left != null)
        getAlphaScore(node.left);
 
    // Calculate the alpha score
    // of the current step
    sum = (sum + node.data) % mod;
 
    // Update alpha score of
    // the journey
    total_sum = (total_sum + sum) % mod;
 
    // Traverse right subtree
    if (node.right != null)
        getAlphaScore(node.right);
 
    // Return
    return total_sum;
}
 
// Function to construct a BST
// from the sorted array []arr
function constructBST(arr, start, end, root)
{
    if (start > end)
        return null;
 
    var mid = parseInt((start + end) / 2);
 
    // Insert root
    if (root == null)
        root = new Node(arr[mid]);
 
    // Construct left subtree
    root.left = constructBST(arr, start,
                             mid - 1, root.left);
 
    // Construct right subtree
    root.right = constructBST(arr, mid + 1,
                              end, root.right);
 
    // Return root
    return root;
}
 
// Driver Code
var arr = [10, 11, 12];
var length = arr.length;
 
// Sort the array
arr.sort();
var root = null;
 
// Construct BST from the sorted array
root = constructBST(arr, 0, length - 1, root);
document.write(getAlphaScore(root));
 
// This code is contributed by rrrtnx.
</script>


Output: 

64

Time Complexity: O(NlogN) 
Auxiliary Space: O(N)
 



Last Updated : 09 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads