15,880,956 members
See more:
```find the maximum difference between any two element in an array.
if an element is arr[i] and another element is arr[j] then difference will be |arr[i]-arr[j]| .```

What I have tried:

```import java.io.*;
import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
n = sc.nextInt();
int []arr=new int[n];
for(int i=0;i<n;++i){
arr[i]=sc.nextInt();
}
ArrayProblem(arr);
}

public static void ArrayProblem(int []arr) {
int n = arr.length;

int max = arr[0]- arr[1];

for (int i = 0; i<n; i++)
{
for (int j = i; j<n; j++)
{
if (arr[j] - arr[i] > max)
max = arr[j] - arr[i];
}
}
System.out.print(max);
}
}```
Posted
Updated 22-Dec-22 1:51am
Richard Deeming 22-Dec-22 6:16am
Because there's either a problem with your code, or a problem with your test cases.

But since, once again, you haven't provided any test cases, or any details of the problem, we can't tell you.
0x01AA 22-Dec-22 6:17am
1 - 4: Difference is -3
2 - 1: Difference is 1

But that is maybe waht you need?
abs(1-4)= 3
abs(2-1)= 1

... and it is mentioned in the task:
|arr[i]-arr[j]|
where the two '|' on the left and on the right mean absolute value ;)

## Solution 1

There, the difference is defined as
`|arr[i]-arr[j]|`

But you are calculating the difference simply as
`arr[j] - arr[i]`

Conclution
Use `Math.abs(value)` to solve the problem.

For more information about `Math.abs()` see e.g. here: Java - abs() Method[^]

I hope it helps.

v2
CPallini 22-Dec-22 7:39am
5.
0x01AA 22-Dec-22 7:46am
Thank you very much.

## Solution 2

Note, however that such code is `O(N^2)`. You might obtain the same result computing the max and min values of the array in a single iteration (i.e. `O(N)`) and then subtracting them.

0x01AA 22-Dec-22 7:56am
Cool finetuning, 5.
CPallini 22-Dec-22 8:00am
Thank you, sir!

Top Experts
Last 24hrsThis month
 Rick York 80 Pete O'Hanlon 20 10071962 10 OriginalGriff 10 mehul bhalala 5
 Pete O'Hanlon 1,840 OriginalGriff 1,365 Graeme_Grant 895 Richard Deeming 798 Dave Kreskowiak 684

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900