Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the maximum value in an array but must be lower than a certain value

Tags:

java

int array[] = new int[]{10, 11, 88, 2, 12, 9};

public static int getMax(int[] inputArray){ 
  int maxValue = inputArray[0];

  for(int i=1;i < inputArray.length;i++){ 
     if(inputArray[i] > maxValue){ 
        maxValue = inputArray[i]; 
     } 
  } 
  return maxValue; 
}

Is there any way to find the maximum value but lower than 88 in the array?


2 Answers

If you use Integers you can do it using a TreeSet

Integer[] values = new Integer[]{10, 11, 88, 2, 12, 9};
NavigableSet<Integer> integers = new TreeSet<>(Arrays.asList(values));

System.out.println(integers.lower(88));
System.out.println(integers.lower(2));
System.out.println(integers.lower(100));

prints out

12
null
88

The javadoc of NavigableSet.lower(E e) says:

Returns the greatest element in this set strictly less than the given element, or null if there is no such element.

like image 79
René Link Avatar answered Dec 23 '25 13:12

René Link


If you use Java8, you can use the Streaming API:

int[] array = new int[]{10, 11, 88, 2, 12, 9};
final int limit = 88;
Optional<Integer> max = Arrays.stream(array).filter(i -> i < limit)
    .boxed().max(Comparator.naturalOrder());

System.out.println("Biggest element smaller than " + limit + " is " + max.get());

Output:

Biggest element smaller than 88 is 12 

It does the following:

  • converts the int array to a stream
  • removes elements from the stream that are greater or equal to the specified limit (.filter)
  • converts the stream to an Integer stream (.boxed)
  • calculates the maximum using the natural order comparator (.max)

The key part of the stream is the filter where the elements that are greater than the limit are removed from the stream.

UPDATE: If the index is also needed

List<Integer> intList = Arrays.asList(0, 11, 88, 2, 12, 9);
final int limit = 88;
IntStream.range(0, intList.size())
        .filter(i -> intList.get(i) < limit)
        .boxed().max(Comparator.comparing(intList::get))
        .ifPresent(resultIndex -> System.out.println("Index " + resultIndex + ", value " + intList.get(resultIndex)));
like image 24
DVarga Avatar answered Dec 23 '25 13:12

DVarga