BackeasyArraysPhonePeMeesho

Extreme Spread Calculation Solution

Problem Statement

Given an array of integers, compute the absolute difference between the largest and smallest values present in the collection.

Example 1
Input
[21, 1]
Output
20

Explanation: Step-by-step: with input [21, 1], we find the maximum value 21 and the minimum value 1. Then, we calculate the absolute difference |21 - 1| = 20.

Example 2
Input
[5, 5, 5]
Output
0

Explanation: Step-by-step: with input [5, 5, 5], we find that all values are the same. Therefore, the maximum and minimum values are the same, resulting in an absolute difference of 0.

Constraints

  • 2 <= array.length <= 1000
  • -10^4 <= array[i] <= 10^4
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

Extreme Spread Calculation — Problem Statement & Solution Guide

ArraysEasyBasic Traversal
TimeO(n)
|
SpaceO(1)

Problem Description

Given an array of integers, compute the absolute difference between the largest and smallest values present in the collection.

Examples

Example 1

Input

[21, 1]

Output

20

Explanation: Step-by-step: with input [21, 1], we find the maximum value 21 and the minimum value 1. Then, we calculate the absolute difference |21 - 1| = 20.

Example 2

Input

[5, 5, 5]

Output

0

Explanation: Step-by-step: with input [5, 5, 5], we find that all values are the same. Therefore, the maximum and minimum values are the same, resulting in an absolute difference of 0.

Constraints

  • 2 <= array.length <= 1000
  • -10^4 <= array[i] <= 10^4

Optimal Approach & Strategy

An optimized approach utilizes built-in functions like Math.max() and Math.min() to directly find the maximum and minimum values in the array, reducing the time complexity. This method is more efficient, especially for large arrays.

Brute Force Approach

The brute force approach involves manually iterating through the array to find the maximum and minimum values. This can be achieved by comparing each element with the current maximum or minimum. However, this method can be inefficient for large arrays.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function extremeSpreadCalculation(array) {
    if (array.length < 2) return 0;
    return Math.max(...array) - Math.min(...array);
}

Asked in Top Tech Interviews

PhonePeMeesho

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.