Picking Numbers

Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to . For example, if your array is , you can create two subarrays meeting the criterion:  and . The maximum length subarray has  elements.
Function Description
Complete the pickingNumbers function in the editor below. It should return an integer that represents the length of the longest array that can be created.
pickingNumbers has the following parameter(s):
  • a: an array of integers


public static int pickingNumbers(List<Integer> a) {
Collections.sort(a);
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
List<Integer> tempList = null;
for (int i = 0; i < a.size(); i++) {
tempList = new ArrayList<Integer>();
for (int j = i; j < a.size(); j++) {
if (a.get(j) - a.get(i) <= 1) {
tempList.add(a.get(j));
} else {
resultList.add(tempList);
tempList = new ArrayList<Integer>();
break;
}
}
resultList.add(tempList);
}
int max =0;
for(int i=0;i<resultList.size();i++) {
if(resultList.get(i).size()>max)max = resultList.get(i).size();
}
//System.out.println(resultList);
return max;
}






Post a Comment

Previous Post Next Post