Range Queries to find the Element having Maximum Digit Sum


Introduction

In this tutorial, we discuss the problem of range queries to find the element having Maximum Digit Sum in C++. To solve the problem, take an array of elements and some queries. The queries denote the indices of the array and using those queries find the array element with the maximum digit sum. Maximum digit sum is the highest sum of two digit numbers (addition of ones and tens place digits) or one digit number. For example: 12, its sum is 3 (1 + 2). In this tutorial, by using the queries find such a number that has a maximum sum digit.

To implement this approach, we use two methods:

  • Naive Approach

  • Constructing a Segment Tree

Demonstration 1

a[] = {1, 44, 16, 11, 18}
Query = [1, 4]

Output

The maximum digit sum element is 18

Explanation

In the above example, the subarray using the query is {44, 16, 11, 18}. The starting index of the input array is 0. To find the element of the maximum digit sum, add two digits in the following way:

44 = 4+4 = 8

16 = 1+6 = 7

11 = 1+1 = 2

18 = 1+8 = 9

Maximum sum is 9 and the element with maximum sum digit is 18.

Demonstration 2

a[] = {12, 44, 55, 45, 63}
Query = [2, 4]

Output

The maximum digit sum element is 55

Explanation

In the above example, the subarray using the query [2, 4] is {55, 45, 63}. To find the element of maximum digit sum find the sum of each element like this:

55 = 5+5 = 10

45 = 4+5 = 9

63 = 6+3 = 9

Maximum sum is 10 and the element with this maximum sum is 55.

C++ Library Functions

Syntax

size(): It is a built-in function of the C++ standard library. It returns the length of the input string.

string_name.size(); 

pow(): It is defined in the <cmath> header file. It takes two parameters and returns the first parameter raised to the power of the second parameter.

pow(a, b);

vector: It is a dynamic array and is defined in the vector header file of C++. Its elements can be easily inserted and deleted.

vector<data_type> vector_name;

ceil(): It is defined in the <cmath> header file. It takes one parameter and returns the nearest greater or equal value of the parameter.

ceil(n);

sizeof(): It is defined in the C++ standard library. It computes the size of the variable, constant, and data type during compile time.

sizeof(variable);

Algorithm 1

  • Initialize an array of elements a[].

  • Define queries to find the indices of the elements.

  • Use a for loop to traverse the array indices defined in the query.

  • Calculate the sum of each element by adding the digits together.

  • Print the number with the maximum digit sum.

Example 1

We implement the task using a simple approach. In this approach, we use a for loop to traverse the array with the starting and ending range defined in the query. Calculate the sum of elements and print the element with the maximum digit sum.

#include <iostream>
using namespace std;
 
// Function for calculating the digit sum 
int digitSum(int no){
    int result = 0;
    while (no > 0){
        result += no % 10;
        no /= 10;
    }
    return result;
}
 
// Function for finding the maximum sum digit number
int maximumDigitSum(int a[], int s, int i, int j){
    int maxs = -1, maxn = -1;
    for (int x = i; x <= j; x++){
        int result = digitSum(a[x]);
        if (result > maxs){
            maxs = result;
            maxn = a[x];
        }
        else if (result == maxs && a[x] > maxn){
            maxn = a[x];
        }
    }
    return maxn;
}
 
// code controller
int main(){
    // Input array
    int a[] = { 11, 14, 34, 51, 32 };
 
    int s = sizeof(a) / sizeof(a[0]);
    int i = 1, j = 4;
    cout << "The maximum digit sum number is : "<<maximumDigitSum(a, s, i, j) << endl;

    return 0;
}

Output

The maximum digit sum number is : 34

Algorithm 2

  • Initialize an array of elements.

  • Specify the range of queries.

  • Construct a segment tree where each node represents an array of elements.

    • The segment tree is constructed by first dividing it into two halves and each node represents two values.

    • Insert values into the left and right children.

  • Each node in the segment tree has two values: number and maxDigitSum.

  • Use the range defined in the Query to find the maximum digit sum by traversing the segment tree.

  • Print the results.

Example 2

Here, we implement the problem in C++ by constructing a segment tree. Construct a segment tree and use the query to find the maximum digit sum. Recursively call the user-defined function maximumDigitSum to iterate the segment tree and calculate the output.

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

// Function to calculate the digit sum of a number
int digitSumNumber(int no){
    int result = 0;
    while (no > 0){
        result += no % 10;
        no /= 10;
    }
    return result;
}

// Function to build the segment tree
void buildSegmentTree(vector<int>& segtree, const vector<int>& a, int l, int h, int p){
    if (l == h){
        segtree[p] = a[l];
        return;
    }
    int m = (l + h) / 2;
    buildSegmentTree(segtree, a, l, m, 2 * p + 1);
    buildSegmentTree(segtree, a, m + 1, h, 2 * p + 2);
    segtree[p] = max(segtree[2 * p + 1], segtree[2 * p + 2]);
}

// Function to query the segment tree for maximum digit sum in a given range
int querySegTree(vector<int>& segtree, int i, int j, int l, int h, int p){
    if (i <= l && j >= h)
        return segtree[p];
    if (i > h || j < l)
        return 0;
    int m = (l + h) / 2;
    return max(querySegTree(segtree, i, j, l, m, 2 * p + 1),
               querySegTree(segtree, i, j, m + 1, h, 2 * p + 2));
}

// Function to initialize the segment tree
int maxDigitSum(const vector<int>& a, int s, int i, int j){
    int segTreeHeight = ceil(log2(s));
    int segTreeSize = 2 * pow(2, segTreeHeight) - 1;
    vector<int> segtree(segTreeSize);

    buildSegmentTree(segtree, a, 0, s - 1, 0);

    return querySegTree(segtree, i, j, 0, s - 1, 0);
}

int main(){
    vector<int> a = {12, 13, 45, 17, 10, 23};
    int s = a.size();
    int i = 1, j = 4;

    int number = maxDigitSum(a, s, i, j);

    cout << "Maximum digit sum in the range [" << i << ", " << j << "]: " << number << endl;

    return 0;
}

Output

Maximum digit sum in the range [1, 4]: 45

Conclusion

We have reached the end of this tutorial on finding the maximum sum of digits in a range of queries. We used two approaches to resolve the task of this tutorial: naive and segment tree. Demonstrated the problem statement with some examples to understand its purpose. During C++ implementation, we initialize an array and define the range of queries to find the maximum sum digit number.

Updated on: 18-Aug-2023

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements