LARGEST VALUE WITH ALL DIGITS 0-5

Consider a non-empty string array inarr whose elements contain only digits from 0 to 5 such that no element in inarr will contain all the digits from 0 to 5. Identify and print outstr using the logic given below:

  • Identify the non-consecutive unique pairs of elements of inarr, starting from left-most element, such that all the digits from 0 to 5 are present at least once in the pair of elements.
  • Form strings for each pair identified by concatenating the elements of the pair such that the order of their occurrence in inarr is preserved.
  • Set outstr with the largest string formed in the above step. If more than one string exists as largest strings, set outstr with the string whose first or second element used for concatenation appear first in inarr when traversing from left to right.
  • Largest string is a string with maximum number of characters If no such pair is identified, print -1

Input Format

Read inarr with the elements separated by ''(comma) from the standard input stream

Constraints

Read the input

Output Format

Print outstr or -1 accordingly to the standard output stream

Sample Input 0

30012,250232, 53201,3004355,124111

Sample Output 0

300123004355


import java.awt.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class ZeroToFive {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] innArr = sc.nextLine().split(",");

ArrayList<String> pairsList = new ArrayList<String>();

for (int i = 0; i < innArr.length-1; i++) {
for (int j = i+1; j < innArr.length ; j++) {
if(j!= i-1 && j!= i+1){
String tempPair = innArr[i].trim()+innArr[j].trim();
String zeroToFive = "012345";
int count = 0;

for (int k = 0; k < zeroToFive.length(); k++) {
if (tempPair.contains(zeroToFive.charAt(k)+"")){
count++;
}
}

if(count == 6) {
pairsList.add(tempPair);
}
}
}
}
if(pairsList.isEmpty()){
System.out.println("-1");
System.exit(0);
}

// Getting lengths of each string into a new list
Integer[] lenArray = new Integer[pairsList.size()];

for (int i = 0; i < lenArray.length; i++) {
lenArray[i] = pairsList.get(i).length();
}

int maxLength = Collections.max(Arrays.asList(lenArray));

ArrayList<String> maxLenPairs = new ArrayList<String>();

for (int i = 0; i < lenArray.length; i++) {
if (lenArray[i] == maxLength){
maxLenPairs.add(pairsList.get(i));
}
}
if(maxLenPairs.isEmpty()){
System.out.println("-1");
}else {
System.out.println(maxLenPairs.get(0));
}
}} 

Comments

Popular posts from this blog

Hackerrank - Quicksort 2 - Sorting

Hackerrank - Day of the Programmer

Hackerrank - UNIQUE ARMSTRONG NUMBER