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

Time:05-05

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 -

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?

CodePudding user response:

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;
}
  • Related