How to find the largest difference in change in an array? - java -
suppose declare array:
int[] arr = {10,2,7,11,3};
the largest (positive) change in array 9 11 - 2 = 9.
how write method find largest change in code smaller integer occurring earlier?
thank you,
i rewrote answer since misunderstood question.
the simplest not efficient way check every change , comparing previous one. if bigger, discard previous 1 , remember 1 instead.
int change = arr[1] - arr[0]; //give initial value, if find bigger change replace for(int = 0; < arr.length - 1; i++) { for(int j = + 1; < arr.length; j++) { if(arr[j]-arr[i] > change) { change = arr[j]-arr[i]; } } }
this still give answer if there no positive changes. if not want that, can modify it. trivial.
keep in mind arr.length - 1
important in outer loop.
Comments
Post a Comment