Olivier - 11 months ago 23

Java Question

Suppose I declare an array:

`int[] arr = {10,2,7,11,3};`

The largest (positive) change in this array would be 9 as 11 - 2 = 9.

How would I write a method that find the largest change in code with the smaller integer occurring earlier?

Thank you,

Answer

**I rewrote the answer since I misunderstood the question.**

The simplest but almost certainly not the most efficient way to do this is to check every change and comparing it to the previous one. If it is bigger, discard the previous one and remember this one instead.

```
int change = arr[1] - arr[0]; //give it an initial value, if we find a bigger change we will replace it
for(int i = 0; i < arr.length - 1; i++) {
for(int j = i + 1; i < arr.length; j++) {
if(arr[j]-arr[i] > change) {
change = arr[j]-arr[i];
}
}
}
```

This will still give an answer even if there are no positive changes. If you do not want that, you can modify it. It is trivial.

Keep in mind that `arr.length - 1`

is important in the outer loop.