Don't miss your Year-End Offer: Up to 20% OFF

Maximum Difference Between Two Elements in an Array

13 February 2024
import java.util.Arrays;

public class HackerAlgo {

    // Find Maximum Difference Between Two Elements in an Array
    public static int findMaxDifference(int[] arr) {
        int n = arr.length;
        if (n < 2) {
System.out.println("Array should contain at least 2 elements.");
            return -1;
        }

Arrays.sort(arr);
        return arr[n - 1] - arr[0];
    }

    public static void main(String[] args) {
        // Example for Find Maximum Difference Between Two Elements in an Array
int[] arr1 = {2, 3, 10, 6, 4, 8, 1};
        int maxDiff1 = findMaxDifference(arr1);
System.out.println("Maximum Difference: " + maxDiff1);

int[] arr2 = {-2, -3, -10, -6, -4, -8, -1};
        int maxDiff2 = findMaxDifference(arr2);
System.out.println("Maximum Difference: " + maxDiff2
# Find Maximum Difference Between Two Elements in an Array
def find_max_difference(arr):
    n = len(arr)
    if n < 2:
print("Array should contain at least 2 elements.")
        return -1

arr.sort()
    return arr[-1] - arr[0]

# Example usage
arr1 = [2, 3, 10, 6, 4, 8, 1]
max_diff1 = find_max_difference(arr1)
print(f"Maximum Difference: {max_diff1}")

arr2 = [-2, -3, -10, -6, -4, -8, -1]
max_diff2 = find_max_difference(arr2)
print(f"Maximum Difference: {max_diff2}")
#include <iostream>
#include <vector>
#include <algorithm>

class HackerAlgo {
public:
    // Find Maximum Difference Between Two Elements in an Array
    static int findMaxDifference(std::vector<int>&arr) {
        int n = arr.size();
        if (n < 2) {
std::cout<< "Array should contain at least 2 elements." <<std::endl;
            return -1;
        }

std::sort(arr.begin(), arr.end());
        return arr[n - 1] - arr[0];
    }
};

int main() {
    // Example for Find Maximum Difference Between Two Elements in an Array
std::vector<int> arr1 = {2, 3, 10, 6, 4, 8, 1};
    int maxDiff1 = HackerAlgo::findMaxDifference(arr1);
std::cout<< "Maximum Difference: " << maxDiff1 << std::endl;

std::vector<int> arr2 = {-2, -3, -10, -6, -4, -8, -1};
    int maxDiff2 = HackerAlgo::findMaxDifference(arr2);
std::cout<< "Maximum Difference: " << maxDiff2 << std::endl;

    return 0
class HackerAlgo {
    // Find Maximum Difference Between Two Elements in an Array
    static findMaxDifference(arr) {
const n = arr.length;
        if (n < 2) {
console.log("Array should contain at least 2 elements.");
            return -1;
        }

arr.sort((a, b) => a - b);
        return arr[n - 1] - arr[0];
    }
}

// Example usage
const arr1 = [2, 3, 10, 6, 4, 8, 1];
const maxDiff1 = HackerAlgo.findMaxDifference(arr1);
console.log(`Maximum Difference: ${maxDiff1}`);

const arr2 = [-2, -3, -10, -6, -4, -8, -1];
const maxDiff2 = HackerAlgo.findMaxDifference(arr2);
console.log(`Maximum Difference: ${maxDiff2}`)

Leave a Comment