Minimum Absolute Difference in an Array

  • + 0 comments
    int minimumAbsoluteDifference(vector<int> arr) {
        
        // Sort the array first
        sort(arr.begin(), arr.end());
        
        // Initialize the minimum difference with a large value
        int ans = abs(arr[1] - arr[0]);
    
        // Compare consecutive elements for the minimum difference
        for (int i = 1; i < arr.size() - 1; i++) {
            ans = min(ans, abs(arr[i + 1] - arr[i]));
        }
    
        return ans;
    }