Extreme Spread Calculation — Problem Statement & Solution Guide
Problem Description
Given an array of integers, compute the absolute difference between the largest and smallest values present in the collection.
Examples
Input
[21, 1]
Output
20
Explanation: Step-by-step: with input [21, 1], we find the maximum value 21 and the minimum value 1. Then, we calculate the absolute difference |21 - 1| = 20.
Input
[5, 5, 5]
Output
0
Explanation: Step-by-step: with input [5, 5, 5], we find that all values are the same. Therefore, the maximum and minimum values are the same, resulting in an absolute difference of 0.
Constraints
- 2 <= array.length <= 1000
- -10^4 <= array[i] <= 10^4
Optimal Approach & Strategy
An optimized approach utilizes built-in functions like Math.max() and Math.min() to directly find the maximum and minimum values in the array, reducing the time complexity. This method is more efficient, especially for large arrays.
Brute Force Approach
The brute force approach involves manually iterating through the array to find the maximum and minimum values. This can be achieved by comparing each element with the current maximum or minimum. However, this method can be inefficient for large arrays.
Verified Code Solutions
function extremeSpreadCalculation(array) {
if (array.length < 2) return 0;
return Math.max(...array) - Math.min(...array);
}#include <iostream>
using namespace std;
int extremeSpreadCalculation(int array[], int size) {
if (size < 2) return 0;
int max = array[0];
int min = array[0];
for (int i = 1; i < size; i++) {
if (array[i] > max) max = array[i];
if (array[i] < min) min = array[i];
}
return max - min;
}
int main() {
int array[] = {12, 5, 8, 21, 3};
int size = sizeof(array)/sizeof(array[0]);
cout<<extremeSpreadCalculation(array, size);
return 0;
}class Solution {
public int extremeSpread(int[] nums) {
return Math.max(nums) - Math.min(nums);
}
}def extremeSpread(nums):
return max(nums) - min(nums)function extremeSpreadCalculation(array) {
if (array.length < 2) return 0;
return Math.max(...array) - Math.min(...array);
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.