(134) 33.7. MAXIMUM AND MINIMUM DIFFERENCE ‐ GREEDY ALGORITHM. - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki

#include <bits/stdc++.h> using namespace std;

int main() { int n; cout << "Enter the size of array: "; cin >> n;

vector<int> a(n);
for (auto &i : a) {
    cin >> i;
}

sort(a.begin(), a.end());
long long mn = 0, mx = 0;

// Calculate maximum and minimum differences
for (int i = 0; i < n / 2; i++) {
    mx += (a[i + n / 2] - a[i]);
    mn += (a[2 * i + 1] - a[2 * i]);
}

cout << "Maximum Diff: " << mx << " Minimum Diff: " << mn << endl;

return 0;

}

/* OUTPUT: Enter the size of array: 4 12 -3 10 0 Maximum Diff: 25 Minimum Diff: 5 */

⚠️ **GitHub.com Fallback** ⚠️