FastPrepMaximum Gap After Sorting

Maximum Gap After Sorting

Tata Consultancy Services logoTata Consultancy Services● EasyFULLTIMEOA
Learn

Problem statement

Given an integer array nums, sort its values in nondecreasing order and find the maximum difference between consecutive values in that sorted order.

Return 0 when nums contains fewer than 2 values.

Implement maximumGap with the integer-array parameter nums and return the maximum adjacent difference as an int.

Function

maximumGap(nums: int[]) → int

Examples

Example 1

nums = [3,6,9,1]return = 3

After sorting, the array is [1, 3, 6, 9]. The adjacent gaps are 2, 3, and 3, so the maximum is 3.

Example 2

nums = [10]return = 0

A single value has no adjacent pair.

Example 3

nums = [-5,-1,-10,4]return = 5

The sorted array is [-10, -5, -1, 4], with gaps 5, 4, and 5.

Constraints

  • 1 <= nums.length <= 200000
  • -10^9 <= nums[i] <= 10^9
  • The answer fits in a signed 32-bit integer.

More Tata Consultancy Services problems

See Tata Consultancy Services hiring insights
public int maximumGap(int[] nums) {
  // write your code here
}
nums[3,6,9,1]
expected3
Checking account…