Learn-dsa..in 30 days!



























CC-6 : Find minimum sum of numbers formed by a list of given digits.

Description:

Given a list of digits, find the minimum sum of numbers that can be formed via the digits.

Test cases and expected outputs:

Input Parameters Expected outputs
The digits : 4,0,2,3 Min num1: 03
Min num2: 24
Min sum: 27

Pseudocode:

We get array of integers nums as input parameter.
Initialize a PriorityQueue instance to be used as Min Heap.
Iterate though nums from index 0 to index nums.length-1:
Add nums[idx]to minHeap.
Initialize String Min1 that will be used to collate the smallest number that can be created using digits from input nums.
Initialize String Min2 that will be used to collate the second smallest number that can be created using digits from input nums.
While minheap size is not 0:
Remove top element of minHeap, append the same to Min1.
Remove top element of minHeap, append the same to Min2.
Parse integers from Min1 and Min2 and add the resultant integers and return the same. This is the smallest sum of numbers that can be formed using the input digits.

Code:

public int findMinSumOf2NumsFormedByDigits(int[] nums) {
	
	PriorityQueue<Integer> minHeap=new PriorityQueue<Integer>();
	for (int iIdx=0; iIdx < nums.length; iIdx++) {
		minHeap.add(nums[iIdx]);
	}
	String min1=new String();
	String min2=new String();
	while (minHeap.size() !=0) {
		min1+=minHeap.remove()+"";
		if (minHeap.size() !=0) {
			min2+=minHeap.remove()+"";
		}
	}
	System.out.println("Min num1: "+ min1);
	System.out.println("Min num2: "+ min2);
	return  Integer.parseInt(min1)+Integer.parseInt(min2);
}

Click here to download and run code and test cases !