1

In a number of array i need length till max value without using sort and

{6,8,2,7,10,3,1}

is it possible to return max-first minimum is that array(10-2=8)?

Digs
  • 193
  • 1
  • 11
  • 1
    It's not clear what you want. In your example `(10-2=8)` where does the 2 comes from ? is 10 the max value of the array ? is 8 from `array[1]` or it's completely different ? do you need the index until the max value (here it should be 5)? – Asoub Sep 29 '16 at 15:28

2 Answers2

1

A simple solution for it is the function Array.short, you can do that:

/*Code not tested*/
Arrays.sort(array);
System.out.println(array[0]); //min value
System.out.println(array[array.length-1]); //max value 

You can see more about this function here: Java: Sort an array

Edit

If you can't sort you can use a algorithm here a good example http://www.java2novice.com/java-sorting-algorithms/bubble-sort/

Community
  • 1
  • 1
Dante
  • 295
  • 2
  • 12
0

The simplest code uses IntStream#summaryStatistics():

IntSummaryStatistics stats = IntStream.of(intArray).summaryStatistics();
int maxDiff = stats.getMax() - stats.getMin();

This approach has O(n) time complexity, which is better than O(n log n) time complexity of sorting the array.

There are faster O(n) algorithms that just calculate the max diff, but this approach is probably good enough for most purposes.

Bohemian
  • 412,405
  • 93
  • 575
  • 722