easyArraysPattern: Basic Traversal

Array Amplitude Solution

Problem Statement

Given an integer array `nums`, calculate its amplitude. The amplitude of an array is defined as the mathematical difference between its maximum element and its minimum element. If the array contains only one element, its amplitude is 0. Write an efficient algorithm to find this value in a single pass.

Examples

Example 1:
Input:nums = [3, 8, 2, 5, 12]
Output:10
Explanation: The maximum element in the array is 12 and the minimum element is 2. The amplitude is 12 - 2 = 10.
Example 2:
Input:nums = [7, 7, 7, 7]
Output:0
Explanation: The maximum element is 7 and the minimum element is 7. The amplitude is 7 - 7 = 0.
Example 3:
Input:nums = [-5, 10, -3, 0, 15, -12]
Output:27
Explanation: The maximum element is 15 and the minimum element is -12. The amplitude is 15 - (-12) = 27.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Time: O(n) Space: O(1)
Initialize min and max variables with the first element of the array. Iterate through the array once, updating the min and max variables as you compare each element, then return the difference. This approach operates in O(n) time and O(1) space.

Run, Test & Submit Code

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

Solve on Interactive Workspace

Tested Solutions

def array_amplitude(nums): if not nums: return 0 min_val = nums[0] max_val = nums[0] for num in nums: if num < min_val: min_val = num if num > max_val: max_val = num return max_val - min_val