Array Amplitude — Problem Statement & Solution Guide
Problem Description
Given an integer array nums, calculate its amplitude. The amplitude of an array is defined as the absolute mathematical difference between its maximum element and its minimum element. If the array contains only one element, its amplitude is 0.
Examples
Input
[8, 2]
Output
6
Explanation: Step-by-step: The array [8, 2] has a max of 8 and a min of 2. To find the amplitude, we take the absolute difference between the max and min, which is |8 - 2| = 6.
Input
[15, -12]
Output
27
Explanation: Step-by-step: The array [15, -12] has a max of 15 and a min of -12. To find the amplitude, we take the absolute difference between the max and min, which is |15 - (-12)| = 27.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Optimal Approach & Strategy
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.
Brute Force Approach
Sort the array in non-decreasing order. Once sorted, the amplitude is simply the difference between the last element and the first element.
Verified Code Solutions
function arrayAmplitude(nums) { let min = nums[0]; let max = nums[0]; for (let i = 1; i < nums.length; i++) { if (nums[i] < min) min = nums[i]; if (nums[i] > max) max = nums[i]; } return Math.abs(max - min); }#include <vector>
#include <algorithm>
#include <climits>
#include <iostream>
long long arrayAmplitude(const std::vector<int>& nums) {
if (nums.empty()) return 0;
int minVal = nums[0];
int maxVal = nums[0];
for (size_t i = 1; i < nums.size(); ++i) {
if (nums[i] < minVal) minVal = nums[i];
if (nums[i] > maxVal) maxVal = nums[i];
}
return (long long)maxVal - (long long)minVal;
}
int main() {
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 arrayAmplitude(nums) { let min = nums[0]; let max = nums[0]; for (let i = 1; i < nums.length; i++) { if (nums[i] < min) min = nums[i]; if (nums[i] > max) max = nums[i]; } return Math.abs(max - min); }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.