Minimum sum of two numbers formed from digits of an array

Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of given array must be used to form the two numbers.

Examples:

Input: [6, 8, 4, 5, 2, 3]
Output: 604
The minimum sum is formed by numbers 
358 and 246

Input: [5, 3, 0, 7, 4]
Output: 82
The minimum sum is formed by numbers 
35 and 047 
class Solution {
    public long solve(int[] a) {
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        StringBuilder num1 = new StringBuilder();
        StringBuilder num2 = new StringBuilder();
        for (int x : a)
            pq.add(x);
        while (!pq.isEmpty()) {
            num1.append(pq.poll() + "");
            if (!pq.isEmpty())
                num2.append(pq.poll() + "");
        }
        long sum = Long.parseLong(num1.toString()) + Long.parseLong(num2.toString());
        return sum;
    }
}

Last updated