Click here to Skip to main content
15,880,956 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
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
Comments
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    
Think about
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 ;)

See also my comments to the question.
Looks like you missed a small detail in your task description.

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.
 
Share this answer
 
v2
Comments
CPallini 22-Dec-22 7:39am    
5.
0x01AA 22-Dec-22 7:46am    
Thank you very much.
0x01AA already gave you the right suggestion for fixing your code.

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.
 
Share this answer
 
Comments
0x01AA 22-Dec-22 7:56am    
Cool finetuning, 5.
CPallini 22-Dec-22 8:00am    
Thank you, sir!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



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