Range Queries to find the Element having Maximum Digit Sum

Given an array Arr of N integers and Q queries, each query having a range from L to R. Find the element having maximum digit sum for the range L to R and if more than one elements have maximum digit sum, then find the maximum element out of those.

Examples:

Input: Arr[] = { 16, 12, 43, 55} 
       Q = 2
       L = 0, R = 3
       L = 0, R = 2

Output: 55
        43

Explanation:
 The range (0, 3) in the 1st query has
 [16, 12, 43, 55]. Here, the digit sums are:
 for 16, 1 + 6 = 7
 for 12, 1 + 2 = 3
 for 43, 4 + 3 = 7
 for 55, 5 + 5 = 10
 Hence, the max digit sum is 10 and 
 max digit sum value is 55.

 The range (0, 2) in the 1st query has
 [16, 12, 43]. Here, the digit sums are:
 for 16, 1 + 6 = 7
 for 12, 1 + 2 = 3
 for 43, 4 + 3 = 7
 Hence, the max digit sum is 7 and 
 max digit sum value is max( 16, 43) = 43. 

Naive Approach:
A simple solution is to run a loop from L to R and calculate the digit sum for each element and find the maximum digit sum element from L to R for every query.

Time Complexity: O(Q * N),
Auxiliary Space: O(1)

Efficient Approach:



  • An efficient approach will be to build a Segment Tree where each node stores two values(value and max_digit_sum), and do a range query on it to find the max digit sum and the corresponding element. But for building the segment tree we have to think about what to store on the nodes of the tree.
  • For finding out the maximum digit sum value, we will require two things, one being the value and the other digit sum. The merging will return two things, the digit sum will store the max(max_digit_sum.left, max_digit_sum.right) in the segment tree and value will contain the corresponding element value.
  • If we have a deep look into it, the max digit sum for any two range combining will either be the max digit sum from the left side or the max digit sum from the right side, whichever is maximum will taken into account.
  • Representation of Segment trees:

    1. Leaf Nodes are the elements of the given array.
    2. Each internal node represents some merging of the leaf nodes. The merging may be different for different problems. For this problem, merging is maximum of the max_digit_sum of leaves under a node.
    3. An array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, right child at 2*i+2 and the parent is at (i-1)/2.
  • Construction of Segment Tree from given array:

    1. We start with a segment arr[0 . . . n-1]. and every time we divide the current segment into two halves(if it has not yet become a segment of length 1), and then call the same procedure on both halves, and for each such segment, we store the max_digit_sum and the value in the corresponding node.
    2. We then do a range query on the segment tree to find out the max_digit_sum for the given range and output the corresponding value.

Below is the C++ implementation of the above approach.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find
// maximum digit sum value
#include <bits/stdc++.h>
using namespace std;
  
// Struct two store two values in one node
struct Node {
    int value;
    int max_digit_sum;
};
  
Node tree[4 * 10000];
  
// Function to find the digit sum
// for a number
int digitSum(int x)
{
    int sum = 0;
    while (x) {
        sum += (x % 10);
        x /= 10;
    }
}
  
// Function to build the segment tree
void build(int a[], int index, int beg, int end)
{
    if (beg == end) {
  
        // If there is one element in array,
        tree[index].value = a[beg];
        tree[index].max_digit_sum = digitSum(a[beg]);
    }
    else {
  
        int mid = (beg + end) / 2;
  
        // If there are more than one elements,
        // then recur for left and right subtrees
        build(a, 2 * index + 1, beg, mid);
        build(a, 2 * index + 2, mid + 1, end);
  
        if (tree[2 * index + 1].max_digit_sum > 
            tree[2 * index + 2].max_digit_sum)
        {
            tree[index].max_digit_sum = 
                tree[2 * index + 1].max_digit_sum;
            tree[index].value =
                tree[2 * index + 1].value;
        }
        else if (tree[2 * index + 2].max_digit_sum >
                 tree[2 * index + 1].max_digit_sum)
        {
            tree[index].max_digit_sum =
                tree[2 * index + 2].max_digit_sum;
            tree[index].value = 
                tree[2 * index + 2].value;
        }
        else
        {
            tree[index].max_digit_sum =
                tree[2 * index + 2].max_digit_sum;
            tree[index].value =
                max(tree[2 * index + 2].value, 
                    tree[2 * index + 1].value);
        }
    }
}
  
// Function to do the range query in the segment
// tree for the maximum digit sum
Node query(int index, int beg, int end,
           int l, int r)
{
    Node result;
    result.value = result.max_digit_sum = -1;
  
    // If segment of this node is outside the given
    // range, then return the minimum valueue.
    if (beg > r || end < l)
        return result;
  
    // If segment of this node is a part of given
    // range, then return the node of the segment
    if (beg >= l && end <= r)
        return tree[index];
  
    int mid = (beg + end) / 2;
  
    // If left segment of this node falls out of
    // range, then recur in the right side of
    // the tree
    if (l > mid)
        return query(2 * index + 2, mid + 1,
                     end, l, r);
  
    // If right segment of this node falls out of
    // range, then recur in the left side of
    // the tree
    if (r <= mid)
        return query(2 * index + 1, beg, 
                     mid, l, r);
  
    // If a part of this segment overlaps with
    // the given range
    Node left = query(2 * index + 1, beg,
                      mid, l, r);
    Node right = query(2 * index + 2, mid + 1,
                       end, l, r);
  
    if (left.max_digit_sum > right.max_digit_sum)
    {
        result.max_digit_sum = left.max_digit_sum;
        result.value = left.value;
    }
    else if (right.max_digit_sum > left.max_digit_sum)
    {
        result.max_digit_sum = right.max_digit_sum;
        result.value = right.value;
    }
    else
    {
        result.max_digit_sum = left.max_digit_sum;
        result.value = max(right.value, left.value);
    }
  
    // Returns the value
    return result;
}
  
// Driver code
int main()
{
  
    int a[] = {16, 12, 43, 55};
  
    // Calculates the length of array
    int N = sizeof(a) / sizeof(a[0]);
  
    // Calls the build function to build
    // the segment tree
    build(a, 0, 0, N - 1);
  
    // Find the max digit-sum valueue between
    // 0th and 3rd index of array
    cout << query(0, 0, N - 1, 0, 3).value
         << endl;
  
    // Find the max digit-sum value between
    // 0th and 2nd index of array
    cout << query(0, 0, N - 1, 0, 2).value
         << endl;
  
    return 0;
}

chevron_right


Output:

55
43

Complexity Analysis:
Time Complexity for tree construction is O(N). There are total 2n-1 nodes, and the value of every node is calculated only once in tree construction.

Time complexity to every query is O(log N).

Time complexity for the problem is O(Q * log N)

competitive-programming-img




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.