Given a number, he recursively finds the sum of its digits till it becomes a single-digit number. He calls this as Digit-Value of a number "
It can be written as :
sumOfDigits(n):
if n is a single digit number:
return n
else:
x = sum of the digits of n
return sumOfDigits(x)
After seeing his interest in this concept, his teacher gave him an interesting problem, that uses the above function defined by him. She gave him an array A of N different numbers. Then she asks him Q queries. In each query, he has to form a set of K numbers from the array and find the sum of Digit-Values of those K numbers. This sum is called the value of that set.
The queries are of the following type :
1 K : Monk must output the maximum value of a set of size K, that can be obtained, as described above.
2 K : Monk must output the minimum value of a set of size K, that can be obtained, as described above.
Monk needs your help to complete this task.
Example:
Input: n = 5, arr ={13, 345, 193, 44444, 100303}, x =1, y = 4
Output: 18
Approach
C++
#include <bits/stdc++.h>using namespace std;long long singleDigit(long long n){long long res = 0;while (n >= 10){res = 0;while (n){res += n % 10;n = n / 10;}n = res;}return n;}int main(){long long n = 5;long long arr[n] = {13, 345, 193, 44444, 100303};for (long long i = 0; i < n; i++)arr[i] = singleDigit(arr[i]);sort(arr, arr + n);long long sum1[n], sum2[n];sum1[n - 1] = arr[n - 1];for (long long i = n - 2; i >= 0; i--)sum1[i] = sum1[i + 1] + arr[i];sum2[0] = arr[0];for (long long i = 1; i < n; i++)sum2[i] = arr[i] + sum2[i - 1];long long x = 1, y = 4;if (x == 1)cout << sum1[n - y] << "\n";elsecout << sum2[y - 1] << "\n";}
Read Interview Questions
Exception Handling Interview Questions
DBMS Interview Questions Set -1
DBMS Interview Questions Set -2
JPA Interview Questions Set -1
Spring Boot Interview Questions Set 1
Spring Boot Interview Questions Set 2
No comments:
Post a Comment