.
import java.util.Arrays;
public class MaxDifference {
private static long difference(
final int[] array,
final int minPos,
final int maxPos
)
{
assert( minPos < maxPos );
assert( array[minPos] < array[maxPos] );
return ( (long) array[maxPos] ) - ( (long) array[minPos] );
}
public static int[] maxDifference( final int[] array ){
if ( array == null|| array.length < 2 )
return null;
int minimaPos = 0;
int minimaValue = array[0];
int minimaPosForMaxDifference = 0;
int maximaPosForMaxDifference = -1;
long maxDifference = -1;
int pos = 0;
while ( pos < array.length - 1 ){
while( pos < array.length - 1 && array[pos] > array[pos + 1])
{
pos++;
}
if ( array[pos] < minimaValue )
{
minimaPos = pos;
minimaValue = array[pos];
}
while( pos < array.length - 1 && array[pos] <= array[pos + 1])
{
pos++;
}
if ( pos > minimaPos )
{
long diff = difference( array, minimaPos, pos );
if ( diff > maxDifference )
{
minimaPosForMaxDifference = minimaPos;
maximaPosForMaxDifference = pos;
maxDifference = diff;
}
}
}
if ( maximaPosForMaxDifference == -1 )
return null;
return new int[]{ minimaPosForMaxDifference, maximaPosForMaxDifference };
}
public static String toDiffString( final int[] array ){
final int[] diff = maxDifference( array );
if ( diff == null )
return String.format(
"%s has no maximum difference",
Arrays.toString(array)
);
else
return String.format(
"%s has maximum difference of %d at %s",
Arrays.toString(array),
difference( array, diff[0], diff[1] ),
Arrays.toString( diff )
);
}
public static void main( final String[] args ){
System.out.println( toDiffString( new int[]{} ) );
System.out.println( toDiffString( new int[]{ 0 } ));
System.out.println( toDiffString( new int[]{ 0, 0 } ));
System.out.println( toDiffString( new int[]{ 1, 0 } ));
System.out.println( toDiffString( new int[]{ 2, 1, 0 } ));
System.out.println( toDiffString( new int[]{ 0, 1, 2 } ));
System.out.println( toDiffString( new int[]{2, 3, 10, 2, 4, 8, 1} ));
System.out.println( toDiffString( new int[]{5,0,3,1,4} ));
System.out.println( toDiffString( new int[]{5,0,3,-1,4} ));
System.out.println( toDiffString( new int[]{ Integer.MIN_VALUE, Integer.MAX_VALUE } ));
}
}
:
[] has no maximum difference
[0] has no maximum difference
[0, 0] has maximum difference of 0 at [0, 1]
[1, 0] has no maximum difference
[2, 1, 0] has no maximum difference
[0, 1, 2] has maximum difference of 2 at [0, 2]
[2, 3, 10, 2, 4, 8, 1] has maximum difference of 8 at [0, 2]
[5, 0, 3, 1, 4] has maximum difference of 4 at [1, 4]
[5, 0, 3, -1, 4] has maximum difference of 5 at [3, 4]
[-2147483648, 2147483647] has maximum difference of 4294967295 at [0, 1]