Magnitude Spread Calculation — Problem Statement & Solution Guide
Problem Description
Given an array of integers, determine the magnitude spread, defined as the difference between the largest and smallest values present within the collection.
Examples
Input
[1, 5]
Output
4
Explanation: Step-by-step: Given the array [1, 5], we first find the largest value, which is 5. Then we find the smallest value, which is 1. The difference between the largest and smallest values is 5 - 1 = 4.
Input
[10, 50]
Output
40
Explanation: Step-by-step: Given the array [10, 50], we first find the largest value, which is 50. Then we find the smallest value, which is 10. The difference between the largest and smallest values is 50 - 10 = 40.
Constraints
- 2 <= nums.length <= 10^4
- -10^6 <= nums[i] <= 10^6
Optimal Approach & Strategy
A more optimized approach would be to use built-in functions to find the maximum and minimum values in one pass, then calculate the spread. This approach would be more efficient and reduce the risk of errors.
Brute Force Approach
The brute force approach would involve iterating through the array to find the maximum and minimum values, then calculating the spread. This approach would be simple to implement but may not be efficient for large arrays.
Verified Code Solutions
function magnitudeSpreadCalculation(nums) { return Math.abs(Math.max(...nums) - Math.min(...nums)); }#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
using namespace std;
int magnitudeSpreadCalculation(vector<int>& nums) {
if (nums.empty()) return numeric_limits<int>::min();
return *max_element(nums.begin(), nums.end()) - *min_element(nums.begin(), nums.end());
}
int main() {
vector<int> nums1 = {14, 2, 8, 31, 7};
cout << magnitudeSpreadCalculation(nums1) << endl;
vector<int> nums2 = {-5, 0, 12, 3};
cout << magnitudeSpreadCalculation(nums2) << endl;
vector<int> nums3 = {};
cout << magnitudeSpreadCalculation(nums3) << endl;
vector<int> nums4 = {5};
cout << magnitudeSpreadCalculation(nums4) << endl;
return 0;
}class Solution {
public int solution(int[] nums) {
return Math.max(nums) - Math.min(nums);
}
}def solution(nums):
return max(nums) - min(nums)function magnitudeSpreadCalculation(nums) { return Math.abs(Math.max(...nums) - Math.min(...nums)); }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.