BackeasyArraysAmazonZomato

Array Amplitude Solution

Problem Statement

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.

Example 1
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.

Example 2
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
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Array Amplitude — Problem Statement & Solution Guide

ArraysEasyBasic Traversal
TimeO(n)
|
SpaceO(1)

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

Example 1

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.

Example 2

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

JavaScript Solution
Time: O(n)
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

AmazonZomato

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.