pickingNumbers Problem HackerRank
Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to .
Example
There are two subarrays meeting the criterion: and . The maximum length subarray has elements.
Function Description
Complete the pickingNumbers function in the editor below.
pickingNumbers has the following parameter(s):
int a[n]: an array of integers
Returns
int: the length of the longest subarray that meets the criterion
Input Format
The first line contains a single integer , the size of the array .
The second line contains space-separated integers, each an .
Solution :
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'pickingNumbers' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER_ARRAY a as parameter.
*/
public static int pickingNumbers(List<Integer> a) {
// Write your code here
Collections.sort(a);
int n=a.size();
int [] arr = new int[n]; // for storing subaarry having diff <=1
int b=0; // for increasing arr index
int count=0; // for length of each subarray having diff <=1
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
int diff=Math.abs(a.get(j)-a.get(i)); // diff find
if(diff<=1)
{
count++;
}
}
arr[b]=count;
b++;
count=0;
}
int maxi=Integer.MIN_VALUE;
for(int k=0;k<n;k++)
{
if(arr[k]>maxi)
{
maxi=arr[k];
}
}
return maxi+1;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> a = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
int result = Result.pickingNumbers(a);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Comments
Post a Comment