easyArraysPattern: Basic Traversal

Magnitude Spread Calculation Solution

Problem Statement

Given an array of integers, determine the magnitude spread, defined as the difference between the largest and smallest values present within the collection.

Examples

Example 1:
Input:nums = [14, 2, 8, 31, 7]
Output:29
Explanation: The maximum value is 31 and the minimum value is 2. The spread is 31 - 2 = 29.
Example 2:
Input:nums = [-5, 0, 12, 3]
Output:17
Explanation: The maximum value is 12 and the minimum value is -5. The spread is 12 - (-5) = 17.

Constraints

  • 2 <= nums.length <= 10^4
  • -10^6 <= nums[i] <= 10^6
Time: O(n) Space: O(1)
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.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

def magnitude_spread_calculation(nums): if not nums: return float('-inf') return max(nums) - min(nums)