Jishan's Log 17: Minimum Absolute Difference in an Array

 Hackerrank Greedy


So this problem is your basic problem.

The Problem:

We are given an array and we are to find the minimum absolute difference.

The Solution:

  1. We will sort the array
  2. Create a storage variable to keep track of minimum difference
  3. We will take the initial abs difference between the first two pairs
  4. if it's 0, we return it
  5. else we iterate through the loop taking two pairs 
    1. if we find their difference is 0, return it
    2. else compare if it is smaller than what we had stored
  6. Finally, we return that storage variable

The Code:

#include <bits/stdc++.h> 

using namespace std;

int min(int a, int b) {
    return a < b ? a : b;
}

int minimumAbsoluteDifference(vector<int> arr) {
    sort(arr.begin(), arr.end());
    
    int res = abs(arr[1] - arr[0]);
    
    if(res == 0) {
        return 0;
    }
    
    for(int i = 0; i < arr.size()-1; ++i) {
        int absDiff = abs(arr[i+1] - arr[i]);
        if (absDiff == 0) {
            return 0;
        }
        else if(res > absDiff) {
            res = absDiff;
        }
    }
    

    
    return res;
}

int main()
{
    
    ios_base::sync_with_stdio(0); 
    cin.tie(0); 
    cout.tie(0);
    
    int n; 
    cin >> n;
    vector<int> arr;
    for(int i = 0; i < n; ++i) {
        int x;
        cin >> x;
        arr.push_back(x);
    }
    
    cout << minimumAbsoluteDifference(arr) << "\n";

    return 0;
}

Comments

Popular posts from this blog

Jishan's Log 14: Codeforces 69A solution

Jishan's Log 12: Codeforces 236A solution

Jishan's Log 13: Codeforces 96A solution