Minimum sum of two numbers formed from digits of an array in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 20-Dec-2019 13:55:37
Advertisements