Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculating the difference between max of even numbers and min of odd numbers of an array

The question statement says –
You are given an array of integers A of size N. Return the difference between the maximum among all even numbers of A and the minimum among all odd numbers in A.

Examples – A = [5, 17, 100, 1] – Ans => 100-1 = 99

My Approach –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Solution {
    public int solve(int[] A) {
        int n = A.length;
        Arrays.sort(A);
        int max = 0;
        int min = 0;
        for(int i=n-1; i>=0; i--) {
            int max1 = A[i];
            if(max1%2 == 0) {
                max = max1;
                break;
            }
        }
        for(int i=0; i<n; i++) {
            int min1 = A[i];
            if(min1%2 == 1) {
                min = min1;
                break;
            }
        }
        int d = max-min;
        return d;
    }
}

The code is working fine for all input values other than negatives and I don’t know why?
Can somebody help me?

>Solution :

You can write code like this. I change a little your code.

public int solve(int[] arr) {
    int n = arr.length;
    Arrays.sort(arr);
    int max = 0;
    int min = 0;
    for(int i=n-1; i>=0; i--) {
        if(arr[i]>max && arr[i]%2==0) {
            max = arr[i];
        }
    }
    for(int i=0; i<n; i++) {
        if(arr[i]<min && arr[i]%2!=0) {
            min= arr[i];
        }
    }
    int d = max-min;
    return d;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading