
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum sum of two numbers formed from digits of an array in C++
Description
Given an array of digits which contains values from 0 to 9. The task is to find the minimum possible sum of two numbers formed from digits of the array. Please note that we have to use all digits of given array
Example
If input array is {7, 5, 1, 3, 2, 4} then minimum sum is 382 as, we can create two number 135 and 247.
Algorithm
- Sort the array in ascending order
- Create two number by picking a digit from sorted array alternatively i.e. from even and odd index
Example
#include <bits/stdc++.h> using namespace std; int getMinSum(int *arr, int n) { sort(arr, arr + n); int a = 0; int b = 0; for (int i = 0; i < n; ++i) { if (i % 2 == 0) { a = a * 10 + arr[i]; } else { b = b * 10 + arr[i]; } } return a + b; } int main() { int arr[] = {7, 5, 1, 3, 2, 4}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum sum = " << getMinSum(arr, n) << endl; return 0; }
When you compile and execute above program. It generates following output −
Output
Minimum sum = 382
- Related Questions & Answers
- Sum of two numbers where one number is represented as array of digits in C++
- Print prime numbers with prime sum of digits in an array
- Recursive sum of digits of a number formed by repeated appends in C++
- Sum of two large numbers in C++
- Minimum Index Sum of Two Lists in C++
- N digit numbers divisible by 5 formed from the M digits in C++
- Minimize the sum of squares of sum of N/2 paired formed by N numbers in C++
- Find the Largest Cube formed by Deleting minimum Digits from a number in C++
- Maximum XOR of Two Numbers in an Array in C++
- Count of numbers from range[L, R] whose sum of digits is Y in C++
- Find last k digits in product of an array numbers in C++
- Program to find minimum digits sum of deleted digits in Python
- Count distinct pairs from two arrays having same sum of digits in C++
- Compute sum of digits in all numbers from 1 to n
- Digits of element wise sum of two arrays into a new array in C++ Program
Advertisements