easyArraysPattern: Basic Traversal
Extreme Spread Calculation Solution
Problem Statement
Given an array of integers, compute the absolute difference between the largest and smallest values present in the collection. The spread is defined as the result of subtracting the minimum value from the maximum value.
Examples
Example 1:
Input:[12, 5, 8, 21, 3]
Output:18
Explanation: The maximum element is 21 and the minimum element is 3. The spread is 21 - 3 = 18.
Example 2:
Input:[7, 7, 7, 7]
Output:0
Explanation: Both the maximum and minimum elements are 7. The spread is 7 - 7 = 0.
Example 3:
Input:[-10, 0, 50, -5]
Output:60
Explanation: The maximum element is 50 and the minimum element is -10. The spread is 50 - (-10) = 60.
Constraints
- 2 <= array.length <= 1000
- -10^4 <= array[i] <= 10^4
Time: O(n) Space: O(1)
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.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def extreme_spread_calculation(array):
return max(array) - min(array) if array else 0