Olivier
Olivier

Reputation: 13

How to find the largest difference in change in an array? - java

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,

Upvotes: 0

Views: 441

Answers (4)

RaminS
RaminS

Reputation: 2239

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.

Upvotes: 1

root
root

Reputation: 1583

Sorting the array would ensure that the smallest number will always be at the front and largest at the back.

     public static void main(String []args){
        int[] arr = {10,2,7,11,3};     
        int diff = findBiggestDiff(arr);
        System.out.println(diff);
     }

     public static int findBiggestDiff(int[] arr){
         Arrays.sort(arr);
        int diff = arr[arr.length-1] - arr[0];
        return diff;
     }

Upvotes: 0

Michael
Michael

Reputation: 786

Interesting question! You could brute-force this pretty easily, as I'm still thinking for a more creative solution.

int [] arr = {5, 4, 3, 2, 1};
int biggestDifference = arr[1]-arr[0];
for (int i = 0; i < arr.length - 1; i++) {
    for (int j = i + 1; j < arr.length; j++) {
        if ((arr[j] - arr[i]) > biggestDifference) {
            biggestDifference = arr[j] - arr[i];
        }
    }
}

Upvotes: 0

Tony Jen
Tony Jen

Reputation: 663

Looks like you want to find the smallest number and the largest number in the list and comparing it with the largest number on the list.

  1. List first item as minimum.
  2. Compare to next item and if greater, assign that number as lesser.
  3. List first item as largest.
  4. Compare to next item and if smaller, assign that number as greater.

At the end of the list, you will have the least and the greatest number. The difference will be the difference between the smallest and the largest.

Hope that helps.

Upvotes: 0

Related Questions